diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/MainFrame.java b/src/MainFrame.java
index 7860e7f..77a51e0 100644
--- a/src/MainFrame.java
+++ b/src/MainFrame.java
@@ -1,152 +1,157 @@
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MainFrame extends JFrame implements ActionListener
{
private JButton sendButton;
private JLabel receiveStatus, localIP;
public MainFrame()
{
setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
// ======================
// Add the title JPanel.
// ======================
JPanel titlePanel = new JPanel();
{
JLabel titleLabel = new JLabel( "P2P File Transfer!" );
titleLabel.setForeground( Color.LIGHT_GRAY );
titleLabel.setFont( new Font( "Sans serif", Font.BOLD, 28 ) );
titlePanel.add( Box.createRigidArea( new Dimension( 1, 30 ) ) );
titlePanel.add( titleLabel );
titlePanel.setBackground( Color.gray );
}
add( titlePanel );
// ======================
// Add the receive label.
// ======================
sendButton = new JButton( "Send a file..." );
sendButton.addActionListener( this );
JPanel receivePanel = new JPanel();
{
// receivePanel.setLayout( new BoxLayout( receivePanel, BoxLayout.Y_AXIS ) );
+ receivePanel.add( Box.createHorizontalGlue() );
+ receivePanel.add( Box.createHorizontalStrut( 10 ) );
receiveStatus = new JLabel( "Server starting..." );
receiveStatus.setFont( receiveStatus.getFont().deriveFont( Font.BOLD ) );
receivePanel.add( receiveStatus );
localIP = new JLabel( "" );
receivePanel.add( localIP );
// receivePanel.add( new JButton( "Copy" ) );
- receivePanel.add( Box.createRigidArea( new Dimension( 5, 5 ) ) );
- receivePanel.setPreferredSize( new Dimension( 400, 100 ) );
+ receivePanel.add( Box.createHorizontalStrut( 5 ) );
+ receivePanel.setPreferredSize( new Dimension( 450, 75 ) );
receivePanel.add( sendButton );
+ receivePanel.add( Box.createHorizontalStrut( 10 ) );
+ receivePanel.add( Box.createHorizontalGlue() );
}
- add( Box.createRigidArea( new Dimension( 1, 10 ) ) );
+ add( Box.createVerticalStrut( 10 ) );
add( receivePanel );
// ================
// Add the footer.
// ================
JPanel footerPanel = new JPanel();
{
JLabel footerLabel = new JLabel( "Version 1.0 / created by Phillip Cohen" );
footerLabel.setForeground( Color.gray );
footerPanel.add( footerLabel );
}
add( footerPanel );
// Other attributes...
updateLabels();
setTitle( "P2P File Transfer!" );
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
- setSize( 450, 180 );
+ setMinimumSize( new Dimension( 350, 175 ));
+ pack();
setResizable( false );
setVisible( true );
addWindowListener( new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing( WindowEvent winEvt )
{
// Perhaps ask user if they want to save any unsaved files first.
System.exit( 0 );
}
} );
}
public void updateLabels()
{
if ( Main.getListener() != null )
{
localIP.setVisible( Main.getListener().isEnabled() );
if ( !Main.getListener().isEnabled() )
receiveStatus.setText( "Server starting..." );
else
{
receiveStatus.setText( "Ready to receive files!" );
localIP.setText( "Your IP is: " + Main.getListener().getServerIP() );
}
}
invalidate();
}
@Override
public void actionPerformed( ActionEvent arg0 )
{
// Create a file chooser
final JFileChooser fc = new JFileChooser();
// In response to a button click:
int returnVal = fc.showOpenDialog( this );
if ( returnVal == JFileChooser.APPROVE_OPTION )
{
File file = fc.getSelectedFile();
if ( fc.getSelectedFile().length() > Long.MAX_VALUE )
{
JOptionPane.showMessageDialog( this, "The file you selected is too big; the max file size that can be transferred is " + Util.formatFileSize( Long.MAX_VALUE ) + "." );
return;
}
// Read the connection address.
String input = JOptionPane.showInputDialog( "Enter the address and port you'd like to send this file to (with port).", "127.0.0.1:" + Listener.DEFAULT_PORT );
try
{
if ( ( input == null ) || ( input.length() < 1 ) )
return;
if ( input.split( ":" ).length == 2 )
{
// Create the main frame, server, and controller.
int port = Integer.parseInt( input.split( ":" )[1] );
new OutgoingTransfer( file, input.split( ":" )[0], port );
}
}
catch ( NumberFormatException ex )
{
JOptionPane.showMessageDialog( null, "Error parsing that port.", "Input error", JOptionPane.ERROR_MESSAGE );
}
}
}
}
| false | true | public MainFrame()
{
setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
// ======================
// Add the title JPanel.
// ======================
JPanel titlePanel = new JPanel();
{
JLabel titleLabel = new JLabel( "P2P File Transfer!" );
titleLabel.setForeground( Color.LIGHT_GRAY );
titleLabel.setFont( new Font( "Sans serif", Font.BOLD, 28 ) );
titlePanel.add( Box.createRigidArea( new Dimension( 1, 30 ) ) );
titlePanel.add( titleLabel );
titlePanel.setBackground( Color.gray );
}
add( titlePanel );
// ======================
// Add the receive label.
// ======================
sendButton = new JButton( "Send a file..." );
sendButton.addActionListener( this );
JPanel receivePanel = new JPanel();
{
// receivePanel.setLayout( new BoxLayout( receivePanel, BoxLayout.Y_AXIS ) );
receiveStatus = new JLabel( "Server starting..." );
receiveStatus.setFont( receiveStatus.getFont().deriveFont( Font.BOLD ) );
receivePanel.add( receiveStatus );
localIP = new JLabel( "" );
receivePanel.add( localIP );
// receivePanel.add( new JButton( "Copy" ) );
receivePanel.add( Box.createRigidArea( new Dimension( 5, 5 ) ) );
receivePanel.setPreferredSize( new Dimension( 400, 100 ) );
receivePanel.add( sendButton );
}
add( Box.createRigidArea( new Dimension( 1, 10 ) ) );
add( receivePanel );
// ================
// Add the footer.
// ================
JPanel footerPanel = new JPanel();
{
JLabel footerLabel = new JLabel( "Version 1.0 / created by Phillip Cohen" );
footerLabel.setForeground( Color.gray );
footerPanel.add( footerLabel );
}
add( footerPanel );
// Other attributes...
updateLabels();
setTitle( "P2P File Transfer!" );
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
setSize( 450, 180 );
setResizable( false );
setVisible( true );
addWindowListener( new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing( WindowEvent winEvt )
{
// Perhaps ask user if they want to save any unsaved files first.
System.exit( 0 );
}
} );
}
| public MainFrame()
{
setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
// ======================
// Add the title JPanel.
// ======================
JPanel titlePanel = new JPanel();
{
JLabel titleLabel = new JLabel( "P2P File Transfer!" );
titleLabel.setForeground( Color.LIGHT_GRAY );
titleLabel.setFont( new Font( "Sans serif", Font.BOLD, 28 ) );
titlePanel.add( Box.createRigidArea( new Dimension( 1, 30 ) ) );
titlePanel.add( titleLabel );
titlePanel.setBackground( Color.gray );
}
add( titlePanel );
// ======================
// Add the receive label.
// ======================
sendButton = new JButton( "Send a file..." );
sendButton.addActionListener( this );
JPanel receivePanel = new JPanel();
{
// receivePanel.setLayout( new BoxLayout( receivePanel, BoxLayout.Y_AXIS ) );
receivePanel.add( Box.createHorizontalGlue() );
receivePanel.add( Box.createHorizontalStrut( 10 ) );
receiveStatus = new JLabel( "Server starting..." );
receiveStatus.setFont( receiveStatus.getFont().deriveFont( Font.BOLD ) );
receivePanel.add( receiveStatus );
localIP = new JLabel( "" );
receivePanel.add( localIP );
// receivePanel.add( new JButton( "Copy" ) );
receivePanel.add( Box.createHorizontalStrut( 5 ) );
receivePanel.setPreferredSize( new Dimension( 450, 75 ) );
receivePanel.add( sendButton );
receivePanel.add( Box.createHorizontalStrut( 10 ) );
receivePanel.add( Box.createHorizontalGlue() );
}
add( Box.createVerticalStrut( 10 ) );
add( receivePanel );
// ================
// Add the footer.
// ================
JPanel footerPanel = new JPanel();
{
JLabel footerLabel = new JLabel( "Version 1.0 / created by Phillip Cohen" );
footerLabel.setForeground( Color.gray );
footerPanel.add( footerLabel );
}
add( footerPanel );
// Other attributes...
updateLabels();
setTitle( "P2P File Transfer!" );
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
setMinimumSize( new Dimension( 350, 175 ));
pack();
setResizable( false );
setVisible( true );
addWindowListener( new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing( WindowEvent winEvt )
{
// Perhaps ask user if they want to save any unsaved files first.
System.exit( 0 );
}
} );
}
|
diff --git a/javafx.navigation/src/org/netbeans/modules/javafx/navigation/CaretListeningTask.java b/javafx.navigation/src/org/netbeans/modules/javafx/navigation/CaretListeningTask.java
index 8be7e0be..e617f451 100644
--- a/javafx.navigation/src/org/netbeans/modules/javafx/navigation/CaretListeningTask.java
+++ b/javafx.navigation/src/org/netbeans/modules/javafx/navigation/CaretListeningTask.java
@@ -1,528 +1,528 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.javafx.navigation;
import com.sun.javafx.api.tree.JavaFXTreePath;
import java.util.EnumSet;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.swing.SwingUtilities;
import org.netbeans.api.javafx.editor.ElementJavadoc;
import org.netbeans.api.javafx.lexer.JFXTokenId;
import org.netbeans.api.javafx.source.CancellableTask;
import org.netbeans.api.javafx.source.CompilationInfo;
import org.netbeans.api.javafx.source.ElementHandle;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.api.lexer.TokenSequence;
import org.openide.filesystems.FileObject;
/**
* This task is called every time the caret position changes in a Java editor.
* <p>
* The task finds the TreePath of the Tree under the caret, converts it to
* an Element and then shows the declartion of the element in Declaration window
* and javadoc in the Javadoc window.
*
* @author Sandip V. Chitale ([email protected])
* @author Anton Chechel - javafx changes
*/
public class CaretListeningTask implements CancellableTask<CompilationInfo> {
private CaretListeningFactory caretListeningFactory;
private FileObject fileObject;
private boolean canceled;
private static ElementHandle<Element> lastEh;
private static ElementHandle<Element> lastEhForNavigator;
private static final Set<JFXTokenId> TOKENS_TO_SKIP = EnumSet.of(JFXTokenId.WS,
JFXTokenId.COMMENT,
JFXTokenId.LINE_COMMENT,
JFXTokenId.DOC_COMMENT);
CaretListeningTask(CaretListeningFactory whichElementJavaSourceTaskFactory, FileObject fileObject) {
this.caretListeningFactory = whichElementJavaSourceTaskFactory;
this.fileObject = fileObject;
}
static void resetLastEH() {
lastEh = null;
}
public void run(CompilationInfo compilationInfo) {
resume();
boolean navigatorShouldUpdate = ClassMemberPanel.getInstance() != null; // XXX set by navigator visible
boolean javadocShouldUpdate = JavafxdocTopComponent.shouldUpdate();
// boolean declarationShouldUpdate = DeclarationTopComponent.shouldUpdate();
if (isCancelled() || (!navigatorShouldUpdate && !javadocShouldUpdate)) {
// if ( isCancelled() || ( !navigatorShouldUpdate && !javadocShouldUpdate && !declarationShouldUpdate ) ) {
return;
}
int lastPosition = CaretListeningFactory.getLastPosition(fileObject);
TokenHierarchy tokens = compilationInfo.getTokenHierarchy();
TokenSequence ts = tokens.tokenSequence();
boolean inJavadoc = false;
int offset = ts.move(lastPosition);
if (ts.moveNext() && ts.token() != null) {
Token token = ts.token();
TokenId tid = token.id();
if (tid == JFXTokenId.DOC_COMMENT) {
inJavadoc = true;
}
if (shouldGoBack(token.toString(), offset < 0 ? 0 : offset)) {
if (ts.movePrevious()) {
token = ts.token();
tid = token.id();
}
}
if (TOKENS_TO_SKIP.contains(tid)) {
skipTokens(ts, TOKENS_TO_SKIP);
}
lastPosition = ts.offset();
}
if (ts.token() != null && ts.token().length() > 1) {
// it is magic for TreeUtilities.pathFor to proper tree
++lastPosition;
}
// try {
// // TODO dirty hack
// CompilationController cc = (CompilationController) compilationInfo;
// if (cc.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) {
// return;
// }
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
// return;
// }
// Find the TreePath for the caret position
JavaFXTreePath tp = compilationInfo.getTreeUtilities().pathFor(lastPosition);
// if cancelled, return
if (isCancelled()) {
return;
}
// Update the navigator
if (navigatorShouldUpdate) {
updateNavigatorSelection(compilationInfo, tp);
}
// Get Element
Element element = compilationInfo.getTrees().getElement(tp);
// if cancelled or no element, return
if (isCancelled()) {
return;
}
if (element == null) {
element = outerElement(compilationInfo, tp);
}
// if is canceled or no element
if (isCancelled() || element == null) {
return;
}
ElementHandle<Element> eh = null;
try {
eh = ElementHandle.create(element);
- } catch (IllegalArgumentException iae) {
+ } catch (Exception ex) {
// can't convert to element handler (incomplete element)
}
if (eh == null) {
return;
}
// Don't update when element is the same
if (lastEh != null && lastEh.signatureEquals(eh) && !inJavadoc) {
// System.out.println(" stoped because os same eh");
return;
} else {
switch (element.getKind()) {
case PACKAGE:
case CLASS:
case INTERFACE:
case ENUM:
case ANNOTATION_TYPE:
case METHOD:
case CONSTRUCTOR:
case INSTANCE_INIT:
case STATIC_INIT:
case FIELD:
case ENUM_CONSTANT:
lastEh = eh;
// Different element clear data
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case PARAMETER:
element = element.getEnclosingElement(); // Take the enclosing method
ElementHandle<Element> eh1 = null;
try {
eh1 = ElementHandle.create(element);
} catch (IllegalArgumentException iae) {
// can't convert to element handler (incomplete element)
}
if (eh1 == null) {
return;
}
lastEh = eh1;
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case LOCAL_VARIABLE:
lastEh = null; // ElementHandle not supported
// setDeclaration(Utils.format(element)); // NOI18N
setJavadoc(null); // NOI18N
return;
default:
// clear
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
return;
}
}
// Compute and set javadoc
if (javadocShouldUpdate) {
computeAndSetJavadoc(compilationInfo, element);
}
if (isCancelled()) {
return;
}
// Compute and set declaration
// if ( declarationShouldUpdate ) {
// computeAndSetDeclaration(compilationInfo, element);
// }
}
// private void setDeclaration(final String declaration) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// DeclarationTopComponent declarationTopComponent = DeclarationTopComponent.findInstance();
// if (declarationTopComponent != null && declarationTopComponent.isOpened()) {
// declarationTopComponent.setDeclaration(declaration);
// }
// }
// });
// }
private void setJavadoc(final ElementJavadoc javadoc) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JavafxdocTopComponent javafxdocTopComponent = JavafxdocTopComponent.findInstance();
if (javafxdocTopComponent != null && javafxdocTopComponent.isOpened()) {
javafxdocTopComponent.setJavadoc(javadoc);
}
}
});
}
/**
* After this method is called the task if running should exit the run
* method immediately.
*/
public final synchronized void cancel() {
canceled = true;
}
protected final synchronized boolean isCancelled() {
return canceled;
}
protected final synchronized void resume() {
canceled = false;
}
private void computeAndSetJavadoc(CompilationInfo compilationInfo, final Element element) {
if (isCancelled()) {
return;
}
// if (compilationInfo.getJavafxTypes().isJFXClass((Symbol) element)) {
// JavaFXSource javaFXSource = compilationInfo.getJavaFXSource();
// FileObject fo = JavaFXSourceUtils.getFile(element, javaFXSource.getCpInfo());
// if (fo != null) {
// javaFXSource = JavaFXSource.forFileObject(fo);
// }
// try {
// javaFXSource.runWhenScanFinished(new Task<CompilationController>() {
// public void run(CompilationController cc) throws Exception {
// setJavadoc(ElementJavadoc.create(cc, element));
// }
// }, true);
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
// }
// } else {
// final ClassIndex classIndex = compilationInfo.getJavaFXSource().getCpInfo().getClassIndex();
// Set<ElementHandle<TypeElement>> declaredTypes = classIndex.getDeclaredTypes(element.getSimpleName().toString(), NameKind.SIMPLE_NAME, EnumSet.allOf(SearchScope.class));
// Iterator<ElementHandle<TypeElement>> it = declaredTypes.iterator();
// if (it.hasNext()) {
// ElementHandle<TypeElement> eh = it.next();
// setJavadoc(ElementJavadoc.create(compilationInfo, eh.resolve(compilationInfo)));
// } else {
setJavadoc(ElementJavadoc.create(compilationInfo, element));
// }
// }
}
// private void computeAndSetDeclaration(CompilationInfo compilationInfo, Element element ) {
//
// if ( element.getKind() == ElementKind.PACKAGE ) {
// setDeclaration("package " + element.toString() + ";");
// return;
// }
//
// if ( isCancelled() ) {
// return;
// }
//
// Tree tree = compilationInfo.getTrees().getTree(element);
//
// if ( isCancelled()) {
// return;
// }
//
// if ( tree != null ) {
// String declaration = unicodeToUtf(tree.toString());
// if (element.getKind() == ElementKind.CONSTRUCTOR) {
// String constructorName = element.getEnclosingElement().getSimpleName().toString();
// declaration = declaration.replaceAll(Pattern.quote("<init>"), Matcher.quoteReplacement(constructorName));
// } else if (element.getKind() == ElementKind.METHOD) {
// if (declaration != null) {
// ExecutableElement executableElement = (ExecutableElement) element;
// AnnotationValue annotationValue = executableElement.getDefaultValue();
// if (annotationValue != null) {
// int lastSemicolon = declaration.lastIndexOf(";"); // NOI18N
// if (lastSemicolon == -1) {
// declaration += " default " + String.valueOf(annotationValue) + ";"; // NOI18N
// } else {
// declaration = declaration.substring(0, lastSemicolon) +
// " default " + String.valueOf(annotationValue) + // NOI18N
// declaration.substring(lastSemicolon);
// }
// }
// }
// } else if ( element.getKind() == ElementKind.FIELD ) {
// declaration = declaration + ";"; // NOI18N
// }
// setDeclaration(declaration);
// return;
// }
// }
// private String unicodeToUtf(String s) {
//
// char buf[] = new char[s.length()];
// s.getChars(0, s.length(), buf, 0);
//
// int j = 0;
// for (int i = 0; i < buf.length; i++) {
//
// if (buf[i] == '\\') {
// i++;
// char ch = buf[i];
// if (ch == 'u') {
// do {
// i++;
// ch = buf[i];
// } while (ch == 'u');
//
// int limit = i + 3;
// if (limit < buf.length) {
// int d = digit(16, buf[i]);
// int code = d;
// while (i < limit && d >= 0) {
// i++;
// ch = buf[i];
// d = digit(16, ch);
// code = (code << 4) + d;
// }
// if (d >= 0) {
// ch = (char) code;
// buf[j] = ch;
// j++;
// //unicodeConversionBp = bp;
// // return;
// }
// }
// // lexError(bp, "illegal.unicode.esc");
// } else {
// i--;
// j++;
// // buf = '\\';
// }
// } else {
// buf[j] = buf[i];
// j++;
// }
// }
//
// return new String(buf, 0, j);
// }
// private int digit(int base, char ch) {
// char c = ch;
// int result = Character.digit(c, base);
// if (result >= 0 && c > 0x7f) {
// // lexError(pos+1, "illegal.nonascii.digit");
// ch = "0123456789abcdef".charAt(result);
// }
// return result;
// }
private void updateNavigatorSelection(CompilationInfo ci, JavaFXTreePath tp) {
// Try to find the declaration we are in
Element e = outerElement(ci, tp);
if (e != null) {
final ElementHandle[] eh = new ElementHandle[1];
try {
eh[0] = ElementHandle.create(e);
} catch (Exception ex) {
System.out.println("* element = " + e);
System.out.println("* element kind = " + e.getKind());
ex.printStackTrace();
// can't convert to element handler (incomplete element)
}
if (eh[0] == null) {
return;
}
if (lastEhForNavigator != null && eh[0].signatureEquals(lastEhForNavigator)) {
return;
}
lastEhForNavigator = eh[0];
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final ClassMemberPanel cmp = ClassMemberPanel.getInstance();
if (cmp != null) {
cmp.selectElement(eh[0]);
}
}
});
}
}
private static Element outerElement(CompilationInfo ci, JavaFXTreePath tp) {
Element e = null;
while (tp != null) {
switch (tp.getLeaf().getJavaFXKind()) {
case FUNCTION_DEFINITION:
case CLASS_DECLARATION:
case COMPILATION_UNIT:
e = ci.getTrees().getElement(tp);
break;
case VARIABLE:
e = ci.getTrees().getElement(tp);
if (SpaceMagicUtils.hasSpiritualInvocation(e)) {
return e;
}
if (e != null && !e.getKind().isField()) {
e = null;
}
break;
}
if (e != null) {
break;
}
tp = tp.getParentPath();
}
return e;
}
private void skipTokens(TokenSequence ts, Set<JFXTokenId> typesToSkip) {
while (ts.moveNext()) {
if (!typesToSkip.contains(ts.token().id())) {
return;
}
}
return;
}
private boolean shouldGoBack(String s, int offset) {
int nlBefore = 0;
int nlAfter = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '\n') { // NOI18N
if (i < offset) {
nlBefore++;
} else {
nlAfter++;
}
if (nlAfter > nlBefore) {
return true;
}
}
}
if (nlBefore < nlAfter) {
return false;
}
return offset < (s.length() - offset);
}
}
| true | true | public void run(CompilationInfo compilationInfo) {
resume();
boolean navigatorShouldUpdate = ClassMemberPanel.getInstance() != null; // XXX set by navigator visible
boolean javadocShouldUpdate = JavafxdocTopComponent.shouldUpdate();
// boolean declarationShouldUpdate = DeclarationTopComponent.shouldUpdate();
if (isCancelled() || (!navigatorShouldUpdate && !javadocShouldUpdate)) {
// if ( isCancelled() || ( !navigatorShouldUpdate && !javadocShouldUpdate && !declarationShouldUpdate ) ) {
return;
}
int lastPosition = CaretListeningFactory.getLastPosition(fileObject);
TokenHierarchy tokens = compilationInfo.getTokenHierarchy();
TokenSequence ts = tokens.tokenSequence();
boolean inJavadoc = false;
int offset = ts.move(lastPosition);
if (ts.moveNext() && ts.token() != null) {
Token token = ts.token();
TokenId tid = token.id();
if (tid == JFXTokenId.DOC_COMMENT) {
inJavadoc = true;
}
if (shouldGoBack(token.toString(), offset < 0 ? 0 : offset)) {
if (ts.movePrevious()) {
token = ts.token();
tid = token.id();
}
}
if (TOKENS_TO_SKIP.contains(tid)) {
skipTokens(ts, TOKENS_TO_SKIP);
}
lastPosition = ts.offset();
}
if (ts.token() != null && ts.token().length() > 1) {
// it is magic for TreeUtilities.pathFor to proper tree
++lastPosition;
}
// try {
// // TODO dirty hack
// CompilationController cc = (CompilationController) compilationInfo;
// if (cc.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) {
// return;
// }
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
// return;
// }
// Find the TreePath for the caret position
JavaFXTreePath tp = compilationInfo.getTreeUtilities().pathFor(lastPosition);
// if cancelled, return
if (isCancelled()) {
return;
}
// Update the navigator
if (navigatorShouldUpdate) {
updateNavigatorSelection(compilationInfo, tp);
}
// Get Element
Element element = compilationInfo.getTrees().getElement(tp);
// if cancelled or no element, return
if (isCancelled()) {
return;
}
if (element == null) {
element = outerElement(compilationInfo, tp);
}
// if is canceled or no element
if (isCancelled() || element == null) {
return;
}
ElementHandle<Element> eh = null;
try {
eh = ElementHandle.create(element);
} catch (IllegalArgumentException iae) {
// can't convert to element handler (incomplete element)
}
if (eh == null) {
return;
}
// Don't update when element is the same
if (lastEh != null && lastEh.signatureEquals(eh) && !inJavadoc) {
// System.out.println(" stoped because os same eh");
return;
} else {
switch (element.getKind()) {
case PACKAGE:
case CLASS:
case INTERFACE:
case ENUM:
case ANNOTATION_TYPE:
case METHOD:
case CONSTRUCTOR:
case INSTANCE_INIT:
case STATIC_INIT:
case FIELD:
case ENUM_CONSTANT:
lastEh = eh;
// Different element clear data
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case PARAMETER:
element = element.getEnclosingElement(); // Take the enclosing method
ElementHandle<Element> eh1 = null;
try {
eh1 = ElementHandle.create(element);
} catch (IllegalArgumentException iae) {
// can't convert to element handler (incomplete element)
}
if (eh1 == null) {
return;
}
lastEh = eh1;
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case LOCAL_VARIABLE:
lastEh = null; // ElementHandle not supported
// setDeclaration(Utils.format(element)); // NOI18N
setJavadoc(null); // NOI18N
return;
default:
// clear
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
return;
}
}
// Compute and set javadoc
if (javadocShouldUpdate) {
computeAndSetJavadoc(compilationInfo, element);
}
if (isCancelled()) {
return;
}
// Compute and set declaration
// if ( declarationShouldUpdate ) {
// computeAndSetDeclaration(compilationInfo, element);
// }
}
| public void run(CompilationInfo compilationInfo) {
resume();
boolean navigatorShouldUpdate = ClassMemberPanel.getInstance() != null; // XXX set by navigator visible
boolean javadocShouldUpdate = JavafxdocTopComponent.shouldUpdate();
// boolean declarationShouldUpdate = DeclarationTopComponent.shouldUpdate();
if (isCancelled() || (!navigatorShouldUpdate && !javadocShouldUpdate)) {
// if ( isCancelled() || ( !navigatorShouldUpdate && !javadocShouldUpdate && !declarationShouldUpdate ) ) {
return;
}
int lastPosition = CaretListeningFactory.getLastPosition(fileObject);
TokenHierarchy tokens = compilationInfo.getTokenHierarchy();
TokenSequence ts = tokens.tokenSequence();
boolean inJavadoc = false;
int offset = ts.move(lastPosition);
if (ts.moveNext() && ts.token() != null) {
Token token = ts.token();
TokenId tid = token.id();
if (tid == JFXTokenId.DOC_COMMENT) {
inJavadoc = true;
}
if (shouldGoBack(token.toString(), offset < 0 ? 0 : offset)) {
if (ts.movePrevious()) {
token = ts.token();
tid = token.id();
}
}
if (TOKENS_TO_SKIP.contains(tid)) {
skipTokens(ts, TOKENS_TO_SKIP);
}
lastPosition = ts.offset();
}
if (ts.token() != null && ts.token().length() > 1) {
// it is magic for TreeUtilities.pathFor to proper tree
++lastPosition;
}
// try {
// // TODO dirty hack
// CompilationController cc = (CompilationController) compilationInfo;
// if (cc.toPhase(Phase.ANALYZED).lessThan(Phase.ANALYZED)) {
// return;
// }
// } catch (IOException ex) {
// Exceptions.printStackTrace(ex);
// return;
// }
// Find the TreePath for the caret position
JavaFXTreePath tp = compilationInfo.getTreeUtilities().pathFor(lastPosition);
// if cancelled, return
if (isCancelled()) {
return;
}
// Update the navigator
if (navigatorShouldUpdate) {
updateNavigatorSelection(compilationInfo, tp);
}
// Get Element
Element element = compilationInfo.getTrees().getElement(tp);
// if cancelled or no element, return
if (isCancelled()) {
return;
}
if (element == null) {
element = outerElement(compilationInfo, tp);
}
// if is canceled or no element
if (isCancelled() || element == null) {
return;
}
ElementHandle<Element> eh = null;
try {
eh = ElementHandle.create(element);
} catch (Exception ex) {
// can't convert to element handler (incomplete element)
}
if (eh == null) {
return;
}
// Don't update when element is the same
if (lastEh != null && lastEh.signatureEquals(eh) && !inJavadoc) {
// System.out.println(" stoped because os same eh");
return;
} else {
switch (element.getKind()) {
case PACKAGE:
case CLASS:
case INTERFACE:
case ENUM:
case ANNOTATION_TYPE:
case METHOD:
case CONSTRUCTOR:
case INSTANCE_INIT:
case STATIC_INIT:
case FIELD:
case ENUM_CONSTANT:
lastEh = eh;
// Different element clear data
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case PARAMETER:
element = element.getEnclosingElement(); // Take the enclosing method
ElementHandle<Element> eh1 = null;
try {
eh1 = ElementHandle.create(element);
} catch (IllegalArgumentException iae) {
// can't convert to element handler (incomplete element)
}
if (eh1 == null) {
return;
}
lastEh = eh1;
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
break;
case LOCAL_VARIABLE:
lastEh = null; // ElementHandle not supported
// setDeclaration(Utils.format(element)); // NOI18N
setJavadoc(null); // NOI18N
return;
default:
// clear
// setDeclaration(""); // NOI18N
setJavadoc(null); // NOI18N
return;
}
}
// Compute and set javadoc
if (javadocShouldUpdate) {
computeAndSetJavadoc(compilationInfo, element);
}
if (isCancelled()) {
return;
}
// Compute and set declaration
// if ( declarationShouldUpdate ) {
// computeAndSetDeclaration(compilationInfo, element);
// }
}
|
diff --git a/bitcoinium/src/main/java/com/veken0m/bitcoinium/BitcoinChartsActivity.java b/bitcoinium/src/main/java/com/veken0m/bitcoinium/BitcoinChartsActivity.java
index 0dd8c85..6d3f0f4 100644
--- a/bitcoinium/src/main/java/com/veken0m/bitcoinium/BitcoinChartsActivity.java
+++ b/bitcoinium/src/main/java/com/veken0m/bitcoinium/BitcoinChartsActivity.java
@@ -1,289 +1,289 @@
package com.veken0m.bitcoinium;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.veken0m.utils.Utils;
import com.xeiam.xchange.bitcoincharts.BitcoinChartsFactory;
import com.xeiam.xchange.bitcoincharts.dto.marketdata.BitcoinChartsTicker;
import java.util.Arrays;
import java.util.Comparator;
public class BitcoinChartsActivity extends SherlockActivity implements OnItemSelectedListener {
private final static Handler mOrderHandler = new Handler();
private BitcoinChartsTicker[] marketData = null;
private final Runnable mBitcoinChartsView;
private final Runnable mError;
private String currencyFilter;
private Dialog dialog = null;
public BitcoinChartsActivity() {
currencyFilter = "SHOW ALL";
mBitcoinChartsView = new Runnable() {
@Override
public void run() {
if (marketData != null) drawBitcoinChartsUI();
}
};
mError = new Runnable() {
@Override
public void run() {
errorOccured();
}
};
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bitcoincharts);
createCurrencyDropdown();
ActionBar actionbar = getSupportActionBar();
actionbar.show();
//KarmaAdsUtils.initAd(this);
viewBitcoinCharts();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.action_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_preferences)
startActivity(new Intent(this, PreferencesActivity.class));
if (item.getItemId() == R.id.action_refresh)
viewBitcoinCharts();
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.bitcoincharts);
if (marketData != null) drawBitcoinChartsUI();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String prevCurrencyfilter = currencyFilter;
currencyFilter = (String) parent.getItemAtPosition(pos);
if (prevCurrencyfilter != null && currencyFilter != null && !currencyFilter.equals(prevCurrencyfilter))
drawBitcoinChartsUI();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
void createCurrencyDropdown() {
// Re-populate the dropdown menu
final String[] dropdownValues = getResources().getStringArray(R.array.bitcoinChartsDropdown);
Spinner spinner = (Spinner) findViewById(R.id.bitcoincharts_currency_spinner);
if (spinner != null) {
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dropdownValues);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(this);
}
}
/**
* Fetch the Bitcoin Charts data
*/
boolean getBitcoinCharts() {
try {
marketData = BitcoinChartsFactory.createInstance().getMarketData();
return true;
} catch (Exception e) {
return false;
}
}
/**
* Draw the Tickers to the screen in a table
*/
void drawBitcoinChartsUI() {
TableLayout bitcoinChartsTable = (TableLayout) findViewById(R.id.bitcoincharts_list);
removeLoadingSpinner();
if (marketData != null && marketData.length > 0 && bitcoinChartsTable != null) {
// Clear table
bitcoinChartsTable.removeAllViews();
// Sort Tickers by volume
Arrays.sort(marketData, new Comparator<BitcoinChartsTicker>() {
@Override
public int compare(BitcoinChartsTicker entry1,
BitcoinChartsTicker entry2) {
return entry2.getVolume().compareTo(entry1.getVolume());
}
});
boolean bBackGroundColor = true;
for (BitcoinChartsTicker data : marketData) {
// Only print active exchanges... vol > 0 or contains selected currency
- if (data.getVolume().intValue() != 0
+ if (data.getVolume().floatValue() != 0.0
&& (currencyFilter.equals("SHOW ALL")
|| data.getCurrency().contains(currencyFilter))) {
final TextView tvSymbol = new TextView(this);
final TextView tvLast = new TextView(this);
final TextView tvVolume = new TextView(this);
final TextView tvHigh = new TextView(this);
final TextView tvLow = new TextView(this);
// final TextView tvAvg = new TextView(this);
// final TextView tvBid = new TextView(this);
// final TextView tvAsk = new TextView(this);
tvSymbol.setText(data.getSymbol());
Utils.setTextViewParams(tvLast, data.getClose());
Utils.setTextViewParams(tvVolume, data.getVolume());
Utils.setTextViewParams(tvLow, data.getLow());
Utils.setTextViewParams(tvHigh, data.getHigh());
// Utils.setTextViewParams(tvAvg, data.getAvg());
// Utils.setTextViewParams(tvBid, data.getBid());
// Utils.setTextViewParams(tvAsk, data.getAsk());
final TableRow newRow = new TableRow(this);
// Toggle background color
bBackGroundColor = !bBackGroundColor;
if (bBackGroundColor)
newRow.setBackgroundColor(Color.BLACK);
else
newRow.setBackgroundColor(Color.rgb(31, 31, 31));
newRow.addView(tvSymbol, Utils.symbolParams);
newRow.addView(tvLast);
newRow.addView(tvVolume);
newRow.addView(tvLow);
newRow.addView(tvHigh);
// newRow.addView(tvBid);
// newRow.addView(tvAsk);
// newRow.addView(tvAvg);
newRow.setPadding(0, 3, 0, 3);
bitcoinChartsTable.addView(newRow);
}
}
} else {
failedToDrawUI();
}
}
private void viewBitcoinCharts() {
if (Utils.isConnected(getApplicationContext())) {
(new bitcoinChartsThread()).start();
} else {
notConnected();
}
}
private class bitcoinChartsThread extends Thread {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout bitcoinChartsLoadSpinner = (LinearLayout) findViewById(R.id.loadSpinner);
if (bitcoinChartsLoadSpinner != null) bitcoinChartsLoadSpinner.setVisibility(View.VISIBLE);
}
});
if (getBitcoinCharts())
mOrderHandler.post(mBitcoinChartsView);
else
mOrderHandler.post(mError);
}
}
private void errorOccured() {
removeLoadingSpinner();
if (dialog == null || !dialog.isShowing()) {
// Display error Dialog
Resources res = getResources();
dialog = Utils.errorDialog(this, String.format(res.getString(R.string.connectionError), "tickers", "Bitcoin Charts"));
}
}
private void notConnected() {
removeLoadingSpinner();
if (dialog == null || !dialog.isShowing()) {
// Display error Dialog
dialog = Utils.errorDialog(this, "No internet connection available", "Internet Connection");
}
}
private void failedToDrawUI() {
removeLoadingSpinner();
if (dialog == null || !dialog.isShowing()) {
// Display error Dialog
dialog = Utils.errorDialog(this, "A problem occurred when generating Bitcoin Charts table", "Error");
}
}
// Remove loading spinner
void removeLoadingSpinner() {
LinearLayout bitcoinChartsLoadSpinner = (LinearLayout) findViewById(R.id.loadSpinner);
if (bitcoinChartsLoadSpinner != null) bitcoinChartsLoadSpinner.setVisibility(View.GONE);
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
}
| true | true | void drawBitcoinChartsUI() {
TableLayout bitcoinChartsTable = (TableLayout) findViewById(R.id.bitcoincharts_list);
removeLoadingSpinner();
if (marketData != null && marketData.length > 0 && bitcoinChartsTable != null) {
// Clear table
bitcoinChartsTable.removeAllViews();
// Sort Tickers by volume
Arrays.sort(marketData, new Comparator<BitcoinChartsTicker>() {
@Override
public int compare(BitcoinChartsTicker entry1,
BitcoinChartsTicker entry2) {
return entry2.getVolume().compareTo(entry1.getVolume());
}
});
boolean bBackGroundColor = true;
for (BitcoinChartsTicker data : marketData) {
// Only print active exchanges... vol > 0 or contains selected currency
if (data.getVolume().intValue() != 0
&& (currencyFilter.equals("SHOW ALL")
|| data.getCurrency().contains(currencyFilter))) {
final TextView tvSymbol = new TextView(this);
final TextView tvLast = new TextView(this);
final TextView tvVolume = new TextView(this);
final TextView tvHigh = new TextView(this);
final TextView tvLow = new TextView(this);
// final TextView tvAvg = new TextView(this);
// final TextView tvBid = new TextView(this);
// final TextView tvAsk = new TextView(this);
tvSymbol.setText(data.getSymbol());
Utils.setTextViewParams(tvLast, data.getClose());
Utils.setTextViewParams(tvVolume, data.getVolume());
Utils.setTextViewParams(tvLow, data.getLow());
Utils.setTextViewParams(tvHigh, data.getHigh());
// Utils.setTextViewParams(tvAvg, data.getAvg());
// Utils.setTextViewParams(tvBid, data.getBid());
// Utils.setTextViewParams(tvAsk, data.getAsk());
final TableRow newRow = new TableRow(this);
// Toggle background color
bBackGroundColor = !bBackGroundColor;
if (bBackGroundColor)
newRow.setBackgroundColor(Color.BLACK);
else
newRow.setBackgroundColor(Color.rgb(31, 31, 31));
newRow.addView(tvSymbol, Utils.symbolParams);
newRow.addView(tvLast);
newRow.addView(tvVolume);
newRow.addView(tvLow);
newRow.addView(tvHigh);
// newRow.addView(tvBid);
// newRow.addView(tvAsk);
// newRow.addView(tvAvg);
newRow.setPadding(0, 3, 0, 3);
bitcoinChartsTable.addView(newRow);
}
}
} else {
failedToDrawUI();
}
}
| void drawBitcoinChartsUI() {
TableLayout bitcoinChartsTable = (TableLayout) findViewById(R.id.bitcoincharts_list);
removeLoadingSpinner();
if (marketData != null && marketData.length > 0 && bitcoinChartsTable != null) {
// Clear table
bitcoinChartsTable.removeAllViews();
// Sort Tickers by volume
Arrays.sort(marketData, new Comparator<BitcoinChartsTicker>() {
@Override
public int compare(BitcoinChartsTicker entry1,
BitcoinChartsTicker entry2) {
return entry2.getVolume().compareTo(entry1.getVolume());
}
});
boolean bBackGroundColor = true;
for (BitcoinChartsTicker data : marketData) {
// Only print active exchanges... vol > 0 or contains selected currency
if (data.getVolume().floatValue() != 0.0
&& (currencyFilter.equals("SHOW ALL")
|| data.getCurrency().contains(currencyFilter))) {
final TextView tvSymbol = new TextView(this);
final TextView tvLast = new TextView(this);
final TextView tvVolume = new TextView(this);
final TextView tvHigh = new TextView(this);
final TextView tvLow = new TextView(this);
// final TextView tvAvg = new TextView(this);
// final TextView tvBid = new TextView(this);
// final TextView tvAsk = new TextView(this);
tvSymbol.setText(data.getSymbol());
Utils.setTextViewParams(tvLast, data.getClose());
Utils.setTextViewParams(tvVolume, data.getVolume());
Utils.setTextViewParams(tvLow, data.getLow());
Utils.setTextViewParams(tvHigh, data.getHigh());
// Utils.setTextViewParams(tvAvg, data.getAvg());
// Utils.setTextViewParams(tvBid, data.getBid());
// Utils.setTextViewParams(tvAsk, data.getAsk());
final TableRow newRow = new TableRow(this);
// Toggle background color
bBackGroundColor = !bBackGroundColor;
if (bBackGroundColor)
newRow.setBackgroundColor(Color.BLACK);
else
newRow.setBackgroundColor(Color.rgb(31, 31, 31));
newRow.addView(tvSymbol, Utils.symbolParams);
newRow.addView(tvLast);
newRow.addView(tvVolume);
newRow.addView(tvLow);
newRow.addView(tvHigh);
// newRow.addView(tvBid);
// newRow.addView(tvAsk);
// newRow.addView(tvAvg);
newRow.setPadding(0, 3, 0, 3);
bitcoinChartsTable.addView(newRow);
}
}
} else {
failedToDrawUI();
}
}
|
diff --git a/jscribble/drawPanel/DrawPanel.java b/jscribble/drawPanel/DrawPanel.java
index 63521ae..6fb3a44 100644
--- a/jscribble/drawPanel/DrawPanel.java
+++ b/jscribble/drawPanel/DrawPanel.java
@@ -1,534 +1,534 @@
// Copyright © 2011 Martin Ueding <[email protected]>
/*
* This file is part of jscribble.
*
* jscribble 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.
*
* jscribble 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
* jscribble. If not, see <http://www.gnu.org/licenses/>.
*/
package jscribble.drawPanel;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import javax.swing.JPanel;
import jscribble.VersionName;
import jscribble.helpers.Localizer;
import jscribble.helpers.Logger;
import jscribble.helpers.SettingsWrapper;
import jscribble.notebook.BufferedImageWrapper;
import jscribble.notebook.NoteBook;
/**
* Displays the current page of a NoteBook. It also listens to the mouse and
* relays the movements to the NoteBook as line drawing commands. It also
* features a command listener for more user interaction.
*
* @author Martin Ueding <[email protected]>
*/
@SuppressWarnings("serial")
public class DrawPanel extends JPanel {
/**
* Color of the help lines.
* TODO Put this into the config.
*/
private static final Color lineColor = new Color(100, 100, 100);
/**
* The spacing between the help lines.
* TODO Put this into the config.
*/
private static final int lineSpacing = 40;
/**
* The NoteBook that is currently displayed.
*/
private NoteBook notebook;
/**
* Handles the image output.
*/
private ImageObserver io = this;
/**
* Whether to display the help panel.
*/
private boolean showHelp = false;
/**
* A list with all the HelpItem to display.
*/
private HelpItem[] helpItems = {
new HelpItem(Localizer.get("h, F1"), Localizer.get("show help")),
new HelpItem(Localizer.get("h, F1, <Esc>"),
Localizer.get("hide help")),
new HelpItem(
Localizer.get("j, <Space>, <Enter>, <DownArrow>, <RightArrow>"),
Localizer.get("go forward")),
new HelpItem(Localizer.get("k, <Backspace>, <UpArrow>, <LeftArrow>"),
Localizer.get("go backward")),
new HelpItem(Localizer.get("f, <Pos1>"), Localizer.get("goto first")),
new HelpItem(Localizer.get("l, <End>"), Localizer.get("goto last")),
new HelpItem(Localizer.get("<Alt-F4> / <CMD-Q>"),
Localizer.get("save & exit")),
new HelpItem(Localizer.get("+"),
Localizer.get("increase onion layers")),
new HelpItem(Localizer.get("-"),
Localizer.get("decrease onion layers")),
new HelpItem(Localizer.get("r"), Localizer.get("toggle ruling")),
new HelpItem(Localizer.get("g"), Localizer.get("toggle graph paper")),
};
/**
* How many images should be composed in a see through way.
*/
private int onionMode;
/**
* A cached image that is used instead of the original images in the onion
* mode to conserve performance. Use it via the getter.
*/
private BufferedImage cachedImage;
/**
* The wrapper for the current image. Use it via the getter.
*/
private BufferedImageWrapper imageWrapper;
/**
* Whether the help splash screen is (still) displayed.
*/
private boolean showHelpSplash = true;
/**
* Which type of ruling is used.
*/
private RulingType ruling = RulingType.NONE;
/**
* Creates a new display panel that will listen to changes from a specific
* NoteBook.
*
* @param notebook the NoteBook to display
*/
public DrawPanel(NoteBook notebook) {
this.notebook = notebook;
// Notify this instance when the notebook was is done drawing.
notebook.setDoneDrawing(new Redrawer(this));
// This handles the painting onto the NoteBook that this DrawPanel
// displays.
PaintListener pl = new PaintListener(this);
addMouseMotionListener(pl);
addMouseListener(pl);
}
/**
* Draws the help screen if needed.
*
* @param g2 Graphics2D to draw in
*/
private void drawHelp(Graphics2D g2) {
if (!showHelp) {
return;
}
// Draw a dark rectangle to write the help text on.
// TODO Put this magic value into the config.
g2.setColor(new Color(0, 0, 0, 200));
g2.fillRoundRect(50, 50, getWidth() - 100, getHeight() - 100, 20,
20);
g2.setColor(Color.WHITE);
// Iterate through the help items and display them.
int i = 0;
// TODO Put these magic values into the config.
int vspacing = 30;
int spacing = 250;
int padding = 70;
for (HelpItem h : helpItems) {
g2.drawString(h.helptext, padding, i * vspacing + padding);
g2.drawString(h.key, spacing + padding, i * vspacing +
padding);
i++;
}
// Print the version identifier.
g2.setColor(Color.GRAY);
g2.drawString(String.format(Localizer.get("Version %s"),
VersionName.version), padding, getHeight() - padding);
}
/**
* Draws a help splash screen at the beginning.
*
* @param g2 Graphics2D to draw in
*/
private void drawHelpSplash(Graphics2D g2) {
if (!showHelpSplash) {
return;
}
// Draw a dark rectangle to write the help text on.
// TODO Put this magic value into the config.
g2.setColor(new Color(0, 0, 0, 100));
Dimension splashSize = new Dimension(getWidth() - 30, 50);
g2.fillRoundRect((getWidth() - splashSize.width) / 2,
(getHeight() - splashSize.height) / 2,
splashSize.width, splashSize.height,
20, 20);
g2.setColor(Color.WHITE);
g2.drawString(Localizer.get("Press h or F1 to get help."),
(getWidth() - splashSize.width) / 2 + 50, getHeight() / 2 + 5);
}
/**
* Draws a line onto the current sheet. If onion mode is used, it will be
* cached in another image. To the user, there will be no difference.
*
* @param x
* @param y
* @param x2
* @param y2
*/
public void drawLine(int x, int y, int x2, int y2) {
if (hasCachedImage()) {
getImageWrapper().drawLine(x, y, x2, y2);
}
notebook.drawLine(x, y, x2, y2);
showHelpSplash = false;
}
/**
* Draws the helping lines if needed.
*
* @param g2 Graphics2D to draw on
*/
private void drawLines(Graphics2D g2) {
if (ruling != RulingType.NONE) {
g2.setColor(lineColor);
// Vertical lines.
if (ruling == RulingType.GRAPH) {
for (int i = lineSpacing; i < getWidth(); i += lineSpacing) {
g2.drawLine(i, 0, i, getHeight());
}
}
// Horizontal lines.
for (int i = lineSpacing; i < getHeight(); i += lineSpacing) {
g2.drawLine(0, i, getWidth(), i);
}
}
}
/**
* Draws the number of onion layers as a string.
*
* @param g2 Graphics2D to draw on
*/
private void drawOnionInfo(Graphics2D g2) {
if (!isOnionMode()) {
return;
}
g2.drawString(String.format(Localizer.get("Onion Layers: %d"),
onionMode), 10, 15);
}
/**
* Draws the page number on top.
*
* @param g2 Graphics2D to draw on
*/
private void drawPageNumber(Graphics2D g2) {
g2.setColor(Color.BLUE);
g2.drawString(String.format(Localizer.get("Page %d/%d"),
notebook.getCurrentSheet().getPagenumber(),
notebook.getSheetCount()), getWidth() / 2, 15);
}
/**
* Draws the scroll panels at the side of the screen if enabled in the
* config.
*
* @param g Context of the current DrawPanel
*/
private void drawScrollPanels(Graphics2D g) {
// Do nothing if the option is not set.
if (!SettingsWrapper.getBoolean("show_scroll_panels", false)) {
return;
}
try {
// Read the dimension of the panel from the config file.
int scrollPanelRadius = SettingsWrapper.getInteger("scroll_panel_width");
int scrollPanelPadding = SettingsWrapper.getInteger("scroll_panel_padding");
// Draw the panels on the sides.
g.setColor(new Color(0, 0, 0, 100));
g.fillRoundRect(-scrollPanelRadius, scrollPanelPadding,
2 * scrollPanelRadius,
getHeight() - 2 * scrollPanelPadding,
scrollPanelRadius, scrollPanelRadius);
g.fillRoundRect(getWidth() - scrollPanelRadius,
scrollPanelPadding, 2 * scrollPanelRadius,
getHeight() - 2 * scrollPanelPadding,
scrollPanelRadius, scrollPanelRadius);
}
catch (NumberFormatException e) {
Logger.handleError(Localizer.get(
"Malformed entry in config file."));
}
}
/**
* Erases a line on the NoteBook. If a cachedImage is used, the line is
* erased on that image as well.
*
* @param x
* @param y
* @param x2
* @param y2
*/
public void eraseLine(int x, int y, int x2, int y2) {
if (hasCachedImage()) {
getImageWrapper().eraseLine(x, y, x2, y2);
// FIXME Prevent erasing of the underlying onion layers, maybe by
// redoing the background image.
}
notebook.eraseLine(x, y, x2, y2);
showHelpSplash = false;
}
/**
* Returns the cached image. This can be the original image if there is no
* onion mode used, or the layered image if used. If there is no image yet,
* it will be created and composed.
*
* @return Image which contains all the drawing information
*/
private BufferedImage getCachedImage() {
// If the onion mode is not enables, the original image can be used.
- if (!isOnionMode() && ruling != RulingType.NONE) {
+ if (!isOnionMode() && ruling == RulingType.NONE) {
return notebook.getCurrentSheet().getImg();
}
if (cachedImage == null) {
// Create a new blank image.
cachedImage = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = (Graphics2D) cachedImage.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, getWidth(), getHeight());
// Go back as many pages as there should be onion layers.
int wentBack = 0;
for (; wentBack < onionMode; wentBack++) {
int prevPageNumber = notebook.getCurrentSheet()
.getPagenumber();
notebook.goBackwards();
if (prevPageNumber == notebook.getCurrentSheet()
.getPagenumber()) {
break;
}
}
// Set the layers to a given opacity.
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP,
(float)(0.8 / Math.max(onionMode, 1))));
// Iterate through from the bottom to the top layer and compose
// the images onto the cache image.
while (wentBack > 0) {
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
// Move on to the next NoteSheet.
wentBack--;
notebook.goForward();
}
drawLines(g2);
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
}
return cachedImage;
}
/**
* Retrieves and initializes the BufferedImageWrapper for the current cached
* image.
*
* @return BufferedImageWrapper of cachedImage
*/
private BufferedImageWrapper getImageWrapper() {
if (imageWrapper == null) {
imageWrapper = new BufferedImageWrapper(cachedImage);
}
return imageWrapper;
}
/**
* Goes one page back.
*/
public void goBackwards() {
resetCachedImage();
notebook.goBackwards();
}
/**
* Goes one page forward.
*/
public void goForward() {
resetCachedImage();
notebook.goForward();
}
/**
* Goes to the first page.
*/
public void gotoFirst() {
resetCachedImage();
notebook.gotoFirst();
}
/**
* Goes to the last page.
*/
public void gotoLast() {
resetCachedImage();
notebook.gotoLast();
}
/**
* Determines whether a cached image is currently used.
*
* @return Whether a cached image is used.
*/
private boolean hasCachedImage() {
return cachedImage != null;
}
/**
* Whether there are any onion layers displayed.
*
* @return Whether there are onion layers.
*/
private boolean isOnionMode() {
return onionMode > 0;
}
/**
* Decreases the onion layers and does additional housekeeping.
*/
public void onionLayersDecrease() {
// Do nothing if there are no layers displayed currently.
if (!isOnionMode()) {
return;
}
resetCachedImage();
onionMode--;
repaint();
}
/**
* Increases the onion layers and does additional housekeeping.
*/
public void onionLayersIncrease() {
resetCachedImage();
onionMode++;
repaint();
}
/**
* Draws the NoteSheet and page number. If lines are on, they are drawn on
* top of the image as well.
*
* @param g graphics context (usually given by Java itself).
*/
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHints(new
RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
// Draw the current image.
g2.drawImage(getCachedImage(), 0, 0, io);
drawPageNumber(g2);
drawOnionInfo(g2);
drawScrollPanels(g2);
drawHelp(g2);
drawHelpSplash(g2);
}
/**
* Resets the cached image after changing pages for instance.
*/
private void resetCachedImage() {
cachedImage = null;
imageWrapper = null;
showHelpSplash = false;
}
/**
* Sets whether the help dialog is displayed.
*/
public void setShowHelp(boolean showHelp) {
this.showHelp = showHelp;
}
/**
* Toggles the display of graph ruling.
*/
public void toggleGraphRuling() {
ruling = ruling == RulingType.GRAPH ? RulingType.NONE : RulingType.GRAPH;
resetCachedImage();
}
/**
* Whether to display the help panel.
*/
public void toggleHelp() {
showHelp = !showHelp;
showHelpSplash = false;
}
/**
* Toggles the display of (line) ruling.
*/
public void toggleRuling() {
ruling = ruling == RulingType.LINE ? RulingType.NONE : RulingType.LINE;
resetCachedImage();
}
}
| true | true | private BufferedImage getCachedImage() {
// If the onion mode is not enables, the original image can be used.
if (!isOnionMode() && ruling != RulingType.NONE) {
return notebook.getCurrentSheet().getImg();
}
if (cachedImage == null) {
// Create a new blank image.
cachedImage = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = (Graphics2D) cachedImage.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, getWidth(), getHeight());
// Go back as many pages as there should be onion layers.
int wentBack = 0;
for (; wentBack < onionMode; wentBack++) {
int prevPageNumber = notebook.getCurrentSheet()
.getPagenumber();
notebook.goBackwards();
if (prevPageNumber == notebook.getCurrentSheet()
.getPagenumber()) {
break;
}
}
// Set the layers to a given opacity.
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP,
(float)(0.8 / Math.max(onionMode, 1))));
// Iterate through from the bottom to the top layer and compose
// the images onto the cache image.
while (wentBack > 0) {
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
// Move on to the next NoteSheet.
wentBack--;
notebook.goForward();
}
drawLines(g2);
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
}
return cachedImage;
}
| private BufferedImage getCachedImage() {
// If the onion mode is not enables, the original image can be used.
if (!isOnionMode() && ruling == RulingType.NONE) {
return notebook.getCurrentSheet().getImg();
}
if (cachedImage == null) {
// Create a new blank image.
cachedImage = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = (Graphics2D) cachedImage.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, getWidth(), getHeight());
// Go back as many pages as there should be onion layers.
int wentBack = 0;
for (; wentBack < onionMode; wentBack++) {
int prevPageNumber = notebook.getCurrentSheet()
.getPagenumber();
notebook.goBackwards();
if (prevPageNumber == notebook.getCurrentSheet()
.getPagenumber()) {
break;
}
}
// Set the layers to a given opacity.
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP,
(float)(0.8 / Math.max(onionMode, 1))));
// Iterate through from the bottom to the top layer and compose
// the images onto the cache image.
while (wentBack > 0) {
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
// Move on to the next NoteSheet.
wentBack--;
notebook.goForward();
}
drawLines(g2);
g2.drawImage(notebook.getCurrentSheet().getImg(), 0, 0, io);
}
return cachedImage;
}
|
diff --git a/src/sisc/nativefun/NativeProcedure.java b/src/sisc/nativefun/NativeProcedure.java
index 1d6cc17..367da7f 100644
--- a/src/sisc/nativefun/NativeProcedure.java
+++ b/src/sisc/nativefun/NativeProcedure.java
@@ -1,93 +1,87 @@
package sisc.nativefun;
import java.io.*;
import sisc.interpreter.*;
import sisc.data.*;
import sisc.io.ValueWriter;
/**
* A native procedure is a Scheme procedure whose behavior when
* applied is implemented in Java code.
*/
public abstract class NativeProcedure extends Procedure implements NamedValue {
/**
* A NativeProcedure instance must implement this method, which
* performs the actual processing specific to that procedure, and
* returns a Value.
*/
public abstract Value doApply(Interpreter r) throws ContinuationException;
public void apply(Interpreter r) throws ContinuationException {
//long start=System.currentTimeMillis();
Expression lxp = r.nxp;
r.nxp = null;
try {
r.acc = doApply(r);
r.returnVLR();
- } catch (ClassCastException cc) {
- error(
- r,
- getName(),
- liMessage(SISCB, "gotunexpectedvalue", cc.getMessage()),
- cc);
} catch (NestedPrimRuntimeException npr) {
r.nxp = lxp; //for error location reporting
error(r, getName(), npr);
} catch (RuntimeException re) {
r.nxp = lxp; //for error location reporting
//re.printStackTrace();
String msg=null;
// We make an exception for the two simplest classes of error,
// since their error itself is descriptive enough.
if (re instanceof PrimRuntimeException ||
re.getClass()==RuntimeException.class) {
msg=re.getMessage();
} else {
msg = javaExceptionToString(re);
}
if (msg == null)
msg = re.getMessage();
error(r, getName(), msg, re);
}
//time+=System.currentTimeMillis()-start;
}
public void display(ValueWriter w) throws IOException {
displayNamedOpaque(w, "native procedure");
}
}
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Second Interpreter of Scheme Code (SISC).
*
* The Initial Developer of the Original Code is Scott G. Miller.
* Portions created by Scott G. Miller are Copyright (C) 2000-2007
* Scott G. Miller. All Rights Reserved.
*
* Contributor(s):
* Matthias Radestock
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
| true | true | public void apply(Interpreter r) throws ContinuationException {
//long start=System.currentTimeMillis();
Expression lxp = r.nxp;
r.nxp = null;
try {
r.acc = doApply(r);
r.returnVLR();
} catch (ClassCastException cc) {
error(
r,
getName(),
liMessage(SISCB, "gotunexpectedvalue", cc.getMessage()),
cc);
} catch (NestedPrimRuntimeException npr) {
r.nxp = lxp; //for error location reporting
error(r, getName(), npr);
} catch (RuntimeException re) {
r.nxp = lxp; //for error location reporting
//re.printStackTrace();
String msg=null;
// We make an exception for the two simplest classes of error,
// since their error itself is descriptive enough.
if (re instanceof PrimRuntimeException ||
re.getClass()==RuntimeException.class) {
msg=re.getMessage();
} else {
msg = javaExceptionToString(re);
}
if (msg == null)
msg = re.getMessage();
error(r, getName(), msg, re);
}
//time+=System.currentTimeMillis()-start;
}
| public void apply(Interpreter r) throws ContinuationException {
//long start=System.currentTimeMillis();
Expression lxp = r.nxp;
r.nxp = null;
try {
r.acc = doApply(r);
r.returnVLR();
} catch (NestedPrimRuntimeException npr) {
r.nxp = lxp; //for error location reporting
error(r, getName(), npr);
} catch (RuntimeException re) {
r.nxp = lxp; //for error location reporting
//re.printStackTrace();
String msg=null;
// We make an exception for the two simplest classes of error,
// since their error itself is descriptive enough.
if (re instanceof PrimRuntimeException ||
re.getClass()==RuntimeException.class) {
msg=re.getMessage();
} else {
msg = javaExceptionToString(re);
}
if (msg == null)
msg = re.getMessage();
error(r, getName(), msg, re);
}
//time+=System.currentTimeMillis()-start;
}
|
diff --git a/core/src/java/liquibase/parser/xml/XMLChangeLogHandler.java b/core/src/java/liquibase/parser/xml/XMLChangeLogHandler.java
index af25c2b6..e3934abe 100644
--- a/core/src/java/liquibase/parser/xml/XMLChangeLogHandler.java
+++ b/core/src/java/liquibase/parser/xml/XMLChangeLogHandler.java
@@ -1,441 +1,441 @@
package liquibase.parser.xml;
import liquibase.ChangeSet;
import liquibase.DatabaseChangeLog;
import liquibase.FileOpener;
import liquibase.change.*;
import liquibase.change.custom.CustomChangeWrapper;
import liquibase.exception.CustomChangeException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.MigrationFailedException;
import liquibase.log.LogFactory;
import liquibase.parser.ChangeLogParser;
import liquibase.preconditions.*;
import liquibase.util.ObjectUtil;
import liquibase.util.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.InputStream;
class XMLChangeLogHandler extends DefaultHandler {
protected Logger log;
private DatabaseChangeLog databaseChangeLog;
private Change change;
private StringBuffer text;
private AndPrecondition rootPrecondition;
private Stack<PreconditionLogic> preconditionLogicStack = new Stack<PreconditionLogic>();
private ChangeSet changeSet;
private FileOpener fileOpener;
private Precondition currentPrecondition;
private Map<String, Object> changeLogParameters = new HashMap<String, Object>();
private boolean inRollback = false;
protected XMLChangeLogHandler(String physicalChangeLogLocation, FileOpener fileOpener, Map<String, Object> properties) {
log = LogFactory.getLogger();
this.fileOpener = fileOpener;
databaseChangeLog = new DatabaseChangeLog(physicalChangeLogLocation);
databaseChangeLog.setPhysicalFilePath(physicalChangeLogLocation);
for (Map.Entry entry : System.getProperties().entrySet()) {
changeLogParameters.put(entry.getKey().toString(), entry.getValue());
}
for (Map.Entry entry : properties.entrySet()) {
changeLogParameters.put(entry.getKey().toString(), entry.getValue());
}
}
public DatabaseChangeLog getDatabaseChangeLog() {
return databaseChangeLog;
}
public void startElement(String uri, String localName, String qName, Attributes baseAttributes) throws SAXException {
Attributes atts = new ExpandingAttributes(baseAttributes);
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("validCheckSum".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
String version = uri.substring(uri.lastIndexOf("/")+1);
if (!version.equals(XMLChangeLogParser.getSchemaVersion())) {
log.warning(databaseChangeLog.getPhysicalFilePath()+" is using schema version "+version+" rather than version "+XMLChangeLogParser.getSchemaVersion());
}
databaseChangeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"),
atts.getValue("author"),
alwaysRun,
runOnChange,
databaseChangeLog.getFilePath(),
databaseChangeLog.getPhysicalFilePath(),
atts.getValue("context"),
atts.getValue("dbms"));
if (StringUtils.trimToNull(atts.getValue("failOnError")) != null) {
changeSet.setFailOnError(Boolean.parseBoolean(atts.getValue("failOnError")));
}
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
String id = atts.getValue("changeSetId");
if (id != null) {
String path = atts.getValue("changeSetPath");
if (path == null) {
path = databaseChangeLog.getFilePath();
}
String author = atts.getValue("changeSetAuthor");
ChangeSet changeSet = databaseChangeLog.getChangeSet(path, author, id);
if (changeSet == null) {
throw new SAXException("Could not find changeSet to use for rollback: "+path+":"+author+":"+id);
} else {
for (Change change : changeSet.getChanges()) {
this.changeSet.addRollbackChange(change);
}
}
}
inRollback = true;
} else if ("preConditions".equals(qName)) {
rootPrecondition = new AndPrecondition();
- rootPrecondition.setSkipOnFail(Boolean.parseBoolean(atts.getValue("skipOnFail")));
+ rootPrecondition.setOnFail(StringUtils.trimToNull(atts.getValue("skipOnFail")));
preconditionLogicStack.push(rootPrecondition);
} else if (rootPrecondition != null) {
currentPrecondition = PreconditionFactory.getInstance().create(qName);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(currentPrecondition, attributeName, attributeValue);
}
preconditionLogicStack.peek().addNestedPrecondition(currentPrecondition);
if (currentPrecondition instanceof PreconditionLogic) {
preconditionLogicStack.push(((PreconditionLogic) currentPrecondition));
}
if ("sqlCheck".equals(qName)) {
text = new StringBuffer();
}
} else if (changeSet != null && change == null) {
change = ChangeFactory.getInstance().create(qName);
change.setChangeSet(changeSet);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException(changeSet, "Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setClassLoader(fileOpener.toClassLoader());
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
change.setUp();
} else if (change != null && "column".equals(qName)) {
ColumnConfig column;
if (change instanceof LoadDataChange) {
column = new LoadDataColumnConfig();
} else {
column = new ColumnConfig();
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof ChangeWithColumns) {
((ChangeWithColumns) change).addColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getLastColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else if (change instanceof ModifyColumnChange) {
lastColumn = ((ModifyColumnChange) change).getColumns().get(((ModifyColumnChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("param".equals(qName)) {
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setParam(atts.getValue("name"), atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "'param' unexpected in " + qName);
}
} else if ("where".equals(qName)) {
text = new StringBuffer();
} else if ("property".equals(qName)) {
if (StringUtils.trimToNull(atts.getValue("file")) == null) {
this.setParameterValue(atts.getValue("name"), atts.getValue("value"));
} else {
Properties props = new Properties();
InputStream propertiesStream = fileOpener.getResourceAsStream(atts.getValue("file"));
if (propertiesStream == null) {
log.info("Could not open properties file "+atts.getValue("file"));
} else {
props.load(propertiesStream);
for (Map.Entry entry : props.entrySet()) {
this.setParameterValue(entry.getKey().toString(), entry.getValue().toString());
}
}
}
} else if (change instanceof ExecuteShellCommandChange && "arg".equals(qName)) {
((ExecuteShellCommandChange) change).addArg(atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "Unexpected tag: " + qName);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error thrown as a SAXException: " + e.getMessage(), e);
e.printStackTrace();
throw new SAXException(e);
}
}
protected void handleIncludedChangeLog(String fileName) throws LiquibaseException {
for (ChangeSet changeSet : new ChangeLogParser(changeLogParameters).parse(fileName, fileOpener).getChangeSets()) {
databaseChangeLog.addChangeSet(changeSet);
}
}
private void setProperty(Object object, String attributeName, String attributeValue) throws IllegalAccessException, InvocationTargetException, CustomChangeException {
if (object instanceof CustomChangeWrapper) {
if (attributeName.equals("class")) {
((CustomChangeWrapper) object).setClass(expandExpressions(attributeValue));
} else {
((CustomChangeWrapper) object).setParam(attributeName, expandExpressions(attributeValue));
}
} else {
ObjectUtil.setProperty(object, attributeName, expandExpressions(attributeValue));
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
String textString = null;
if (text != null && text.length() > 0) {
textString = expandExpressions(StringUtils.trimToNull(text.toString()));
}
try {
if (rootPrecondition != null) {
if ("preConditions".equals(qName)) {
if (changeSet == null) {
databaseChangeLog.setPreconditions(rootPrecondition);
handlePreCondition(rootPrecondition);
} else {
changeSet.setPreconditions(rootPrecondition);
}
rootPrecondition = null;
} else if ("and".equals(qName)) {
preconditionLogicStack.pop();
currentPrecondition = null;
} else if ("or".equals(qName)) {
preconditionLogicStack.pop();
currentPrecondition = null;
} else if ("not".equals(qName)) {
preconditionLogicStack.pop();
currentPrecondition = null;
} else if (qName.equals("sqlCheck")) {
((SqlPrecondition) currentPrecondition).setSql(textString);
currentPrecondition = null;
} else if (qName.equals("customPrecondition")) {
((CustomPreconditionWrapper) currentPrecondition).setClassLoader(fileOpener.toClassLoader());
}
} else if (changeSet != null && "rollback".equals(qName)) {
changeSet.addRollBackSQL(textString);
inRollback = false;
} else if (change != null && change instanceof RawSQLChange && "comment".equals(qName)) {
((RawSQLChange) change).setComments(textString);
text = new StringBuffer();
} else if (change != null && "where".equals(qName)) {
if (change instanceof UpdateDataChange) {
((UpdateDataChange) change).setWhereClause(textString);
} else if (change instanceof DeleteDataChange) {
((DeleteDataChange) change).setWhereClause(textString);
} else {
throw new RuntimeException("Unexpected change type: "+change.getClass().getName());
}
text = new StringBuffer();
} else if (change != null && change instanceof CreateProcedureChange && "comment".equals(qName)) {
((CreateProcedureChange) change).setComments(textString);
text = new StringBuffer();
} else if (changeSet != null && "comment".equals(qName)) {
changeSet.setComments(textString);
text = new StringBuffer();
} else if (changeSet != null && "changeSet".equals(qName)) {
handleChangeSet(changeSet);
changeSet = null;
} else if (change != null && qName.equals(change.getTagName())) {
if (textString != null) {
if (change instanceof RawSQLChange) {
((RawSQLChange) change).setSql(textString);
} else if (change instanceof CreateProcedureChange) {
((CreateProcedureChange) change).setProcedureBody(textString);
} else if (change instanceof CreateViewChange) {
((CreateViewChange) change).setSelectQuery(textString);
} else if (change instanceof InsertDataChange) {
List<ColumnConfig> columns = ((InsertDataChange) change).getColumns();
columns.get(columns.size() - 1).setValue(textString);
} else if (change instanceof UpdateDataChange) {
List<ColumnConfig> columns = ((UpdateDataChange) change).getColumns();
columns.get(columns.size() - 1).setValue(textString);
} else {
throw new RuntimeException("Unexpected text in " + change.getTagName());
}
}
text = null;
if (inRollback) {
changeSet.addRollbackChange(change);
} else {
changeSet.addChange(change);
}
change = null;
} else if (changeSet != null && "validCheckSum".equals(qName)) {
changeSet.addValidCheckSum(text.toString());
text = null;
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error thrown as a SAXException: " + e.getMessage(), e);
throw new SAXException(databaseChangeLog.getPhysicalFilePath() + ": " + e.getMessage(), e);
}
}
protected String expandExpressions(String text) {
if (text == null) {
return null;
}
Pattern expressionPattern = Pattern.compile("(\\$\\{[^\\}]+\\})");
Matcher matcher = expressionPattern.matcher(text);
String originalText = text;
while (matcher.find()) {
String expressionString = originalText.substring(matcher.start(), matcher.end());
String valueTolookup = expressionString.replaceFirst("\\$\\{","").replaceFirst("\\}$", "");
int dotIndex = valueTolookup.indexOf('.');
Object value = getParameterValue(valueTolookup);
if (value != null) {
text = text.replace(expressionString, value.toString());
}
}
return text;
}
protected void handlePreCondition(@SuppressWarnings("unused")Precondition precondition) {
databaseChangeLog.setPreconditions(rootPrecondition);
}
protected void handleChangeSet(ChangeSet changeSet) {
databaseChangeLog.addChangeSet(changeSet);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (text != null) {
text.append(new String(ch, start, length));
}
}
public Object getParameterValue(String paramter) {
return changeLogParameters.get(paramter);
}
public void setParameterValue(String paramter, Object value) {
if (!changeLogParameters.containsKey(paramter)) {
changeLogParameters.put(paramter, value);
}
}
/**
* Wrapper for Attributes that expands the value as needed
*/
private class ExpandingAttributes implements Attributes {
private Attributes attributes;
private ExpandingAttributes(Attributes attributes) {
this.attributes = attributes;
}
public int getLength() {
return attributes.getLength();
}
public String getURI(int index) {
return attributes.getURI(index);
}
public String getLocalName(int index) {
return attributes.getLocalName(index);
}
public String getQName(int index) {
return attributes.getQName(index);
}
public String getType(int index) {
return attributes.getType(index);
}
public String getValue(int index) {
return attributes.getValue(index);
}
public int getIndex(String uri, String localName) {
return attributes.getIndex(uri, localName);
}
public int getIndex(String qName) {
return attributes.getIndex(qName);
}
public String getType(String uri, String localName) {
return attributes.getType(uri, localName);
}
public String getType(String qName) {
return attributes.getType(qName);
}
public String getValue(String uri, String localName) {
return expandExpressions(attributes.getValue(uri, localName));
}
public String getValue(String qName) {
return expandExpressions(attributes.getValue(qName));
}
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes baseAttributes) throws SAXException {
Attributes atts = new ExpandingAttributes(baseAttributes);
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("validCheckSum".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
String version = uri.substring(uri.lastIndexOf("/")+1);
if (!version.equals(XMLChangeLogParser.getSchemaVersion())) {
log.warning(databaseChangeLog.getPhysicalFilePath()+" is using schema version "+version+" rather than version "+XMLChangeLogParser.getSchemaVersion());
}
databaseChangeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"),
atts.getValue("author"),
alwaysRun,
runOnChange,
databaseChangeLog.getFilePath(),
databaseChangeLog.getPhysicalFilePath(),
atts.getValue("context"),
atts.getValue("dbms"));
if (StringUtils.trimToNull(atts.getValue("failOnError")) != null) {
changeSet.setFailOnError(Boolean.parseBoolean(atts.getValue("failOnError")));
}
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
String id = atts.getValue("changeSetId");
if (id != null) {
String path = atts.getValue("changeSetPath");
if (path == null) {
path = databaseChangeLog.getFilePath();
}
String author = atts.getValue("changeSetAuthor");
ChangeSet changeSet = databaseChangeLog.getChangeSet(path, author, id);
if (changeSet == null) {
throw new SAXException("Could not find changeSet to use for rollback: "+path+":"+author+":"+id);
} else {
for (Change change : changeSet.getChanges()) {
this.changeSet.addRollbackChange(change);
}
}
}
inRollback = true;
} else if ("preConditions".equals(qName)) {
rootPrecondition = new AndPrecondition();
rootPrecondition.setSkipOnFail(Boolean.parseBoolean(atts.getValue("skipOnFail")));
preconditionLogicStack.push(rootPrecondition);
} else if (rootPrecondition != null) {
currentPrecondition = PreconditionFactory.getInstance().create(qName);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(currentPrecondition, attributeName, attributeValue);
}
preconditionLogicStack.peek().addNestedPrecondition(currentPrecondition);
if (currentPrecondition instanceof PreconditionLogic) {
preconditionLogicStack.push(((PreconditionLogic) currentPrecondition));
}
if ("sqlCheck".equals(qName)) {
text = new StringBuffer();
}
} else if (changeSet != null && change == null) {
change = ChangeFactory.getInstance().create(qName);
change.setChangeSet(changeSet);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException(changeSet, "Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setClassLoader(fileOpener.toClassLoader());
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
change.setUp();
} else if (change != null && "column".equals(qName)) {
ColumnConfig column;
if (change instanceof LoadDataChange) {
column = new LoadDataColumnConfig();
} else {
column = new ColumnConfig();
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof ChangeWithColumns) {
((ChangeWithColumns) change).addColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getLastColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else if (change instanceof ModifyColumnChange) {
lastColumn = ((ModifyColumnChange) change).getColumns().get(((ModifyColumnChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("param".equals(qName)) {
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setParam(atts.getValue("name"), atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "'param' unexpected in " + qName);
}
} else if ("where".equals(qName)) {
text = new StringBuffer();
} else if ("property".equals(qName)) {
if (StringUtils.trimToNull(atts.getValue("file")) == null) {
this.setParameterValue(atts.getValue("name"), atts.getValue("value"));
} else {
Properties props = new Properties();
InputStream propertiesStream = fileOpener.getResourceAsStream(atts.getValue("file"));
if (propertiesStream == null) {
log.info("Could not open properties file "+atts.getValue("file"));
} else {
props.load(propertiesStream);
for (Map.Entry entry : props.entrySet()) {
this.setParameterValue(entry.getKey().toString(), entry.getValue().toString());
}
}
}
} else if (change instanceof ExecuteShellCommandChange && "arg".equals(qName)) {
((ExecuteShellCommandChange) change).addArg(atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "Unexpected tag: " + qName);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error thrown as a SAXException: " + e.getMessage(), e);
e.printStackTrace();
throw new SAXException(e);
}
}
| public void startElement(String uri, String localName, String qName, Attributes baseAttributes) throws SAXException {
Attributes atts = new ExpandingAttributes(baseAttributes);
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("validCheckSum".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
String version = uri.substring(uri.lastIndexOf("/")+1);
if (!version.equals(XMLChangeLogParser.getSchemaVersion())) {
log.warning(databaseChangeLog.getPhysicalFilePath()+" is using schema version "+version+" rather than version "+XMLChangeLogParser.getSchemaVersion());
}
databaseChangeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"),
atts.getValue("author"),
alwaysRun,
runOnChange,
databaseChangeLog.getFilePath(),
databaseChangeLog.getPhysicalFilePath(),
atts.getValue("context"),
atts.getValue("dbms"));
if (StringUtils.trimToNull(atts.getValue("failOnError")) != null) {
changeSet.setFailOnError(Boolean.parseBoolean(atts.getValue("failOnError")));
}
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
String id = atts.getValue("changeSetId");
if (id != null) {
String path = atts.getValue("changeSetPath");
if (path == null) {
path = databaseChangeLog.getFilePath();
}
String author = atts.getValue("changeSetAuthor");
ChangeSet changeSet = databaseChangeLog.getChangeSet(path, author, id);
if (changeSet == null) {
throw new SAXException("Could not find changeSet to use for rollback: "+path+":"+author+":"+id);
} else {
for (Change change : changeSet.getChanges()) {
this.changeSet.addRollbackChange(change);
}
}
}
inRollback = true;
} else if ("preConditions".equals(qName)) {
rootPrecondition = new AndPrecondition();
rootPrecondition.setOnFail(StringUtils.trimToNull(atts.getValue("skipOnFail")));
preconditionLogicStack.push(rootPrecondition);
} else if (rootPrecondition != null) {
currentPrecondition = PreconditionFactory.getInstance().create(qName);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(currentPrecondition, attributeName, attributeValue);
}
preconditionLogicStack.peek().addNestedPrecondition(currentPrecondition);
if (currentPrecondition instanceof PreconditionLogic) {
preconditionLogicStack.push(((PreconditionLogic) currentPrecondition));
}
if ("sqlCheck".equals(qName)) {
text = new StringBuffer();
}
} else if (changeSet != null && change == null) {
change = ChangeFactory.getInstance().create(qName);
change.setChangeSet(changeSet);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException(changeSet, "Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setClassLoader(fileOpener.toClassLoader());
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
change.setUp();
} else if (change != null && "column".equals(qName)) {
ColumnConfig column;
if (change instanceof LoadDataChange) {
column = new LoadDataColumnConfig();
} else {
column = new ColumnConfig();
}
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof ChangeWithColumns) {
((ChangeWithColumns) change).addColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getLastColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else if (change instanceof ModifyColumnChange) {
lastColumn = ((ModifyColumnChange) change).getColumns().get(((ModifyColumnChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("param".equals(qName)) {
if (change instanceof CustomChangeWrapper) {
((CustomChangeWrapper) change).setParam(atts.getValue("name"), atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "'param' unexpected in " + qName);
}
} else if ("where".equals(qName)) {
text = new StringBuffer();
} else if ("property".equals(qName)) {
if (StringUtils.trimToNull(atts.getValue("file")) == null) {
this.setParameterValue(atts.getValue("name"), atts.getValue("value"));
} else {
Properties props = new Properties();
InputStream propertiesStream = fileOpener.getResourceAsStream(atts.getValue("file"));
if (propertiesStream == null) {
log.info("Could not open properties file "+atts.getValue("file"));
} else {
props.load(propertiesStream);
for (Map.Entry entry : props.entrySet()) {
this.setParameterValue(entry.getKey().toString(), entry.getValue().toString());
}
}
}
} else if (change instanceof ExecuteShellCommandChange && "arg".equals(qName)) {
((ExecuteShellCommandChange) change).addArg(atts.getValue("value"));
} else {
throw new MigrationFailedException(changeSet, "Unexpected tag: " + qName);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error thrown as a SAXException: " + e.getMessage(), e);
e.printStackTrace();
throw new SAXException(e);
}
}
|
diff --git a/src/test/java/lcmc/utilities/TestSuite1.java b/src/test/java/lcmc/utilities/TestSuite1.java
index 4207601a..765b41e0 100644
--- a/src/test/java/lcmc/utilities/TestSuite1.java
+++ b/src/test/java/lcmc/utilities/TestSuite1.java
@@ -1,393 +1,397 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
* Copyright (C) 2011-2012, Rastislav Levrinc.
*
* DRBD Management Console 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.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.utilities;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.File;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import junit.framework.TestSuite;
import junit.framework.TestCase;
import lcmc.gui.TerminalPanel;
import lcmc.data.Host;
import lcmc.data.Cluster;
/**
* This class provides tools for testing.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public final class TestSuite1 {
/** Singleton. */
private static TestSuite1 instance = null;
/** Whether to test interactive elements. ant -Dinteractive=true. */
public static final boolean INTERACTIVE =
"true".equals(System.getProperty("test.interactive"));
/** Whether to test version. ant -Dconnect=true. */
public static final boolean CONNECT_LINBIT =
"true".equals(System.getProperty("test.connect"));
/** Whether to connect to test1,test2... clusters. ant -Dcluster=true. */
public static final boolean CLUSTER =
"true".equals(System.getProperty("test.cluster"));
/** Factor that multiplies number of tests. */
public static final String FACTOR = System.getProperty("test.factor");
public static final String PASSWORD = System.getProperty("test.password");
public static final String ID_DSA_KEY = System.getProperty("test.dsa");
public static final String ID_RSA_KEY = System.getProperty("test.rsa");
/** Skip tests that take long time. */
public static final boolean QUICK = "true".equals(
System.getProperty("test.quick"));
public static final String INFO_STRING = "INFO: ";
public static final String DEBUG_STRING = "DEBUG: ";
public static final String ERROR_STRING = "ERROR: ";
public static final String APPWARNING_STRING = "APPWARNING: ";
public static final String APPERROR_STRING = "APPERROR: ";
public static final int NUMBER_OF_HOSTS;
static {
if (Tools.isNumber(System.getProperty("test.count"))) {
NUMBER_OF_HOSTS = Integer.parseInt(
System.getProperty("test.count"));
} else {
NUMBER_OF_HOSTS = 3;
}
}
public static final List<Host> HOSTS = new ArrayList<Host>();
public static final String TEST_HOSTNAME =
System.getenv("LCMC_TEST_HOSTNAME");
public static final String TEST_USERNAME =
System.getenv("LCMC_TEST_USERNAME");
/** Private constructor. */
private TestSuite1() {
/* no instantiation possible. */
}
/** This is to make this class a singleton. */
public static TestSuite1 getInstance() {
synchronized (TestSuite1.class) {
if (instance == null) {
instance = new TestSuite1();
}
}
return instance;
}
//private static PrintStream realOut = System.out;
private static PrintStream realOut = new PrintStream(
new FileOutputStream(FileDescriptor.out));
private static StringBuilder stdout = new StringBuilder();
private static OutputStream out = new OutputStream() {
@Override
public void write(final int b) throws IOException {
stdout.append(String.valueOf((char) b));
}
@Override
public void write(final byte[] b,
final int off,
final int len) throws IOException {
stdout.append(new String(b, off, len));
}
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
};
/** Clears stdout. Call it, if something writes to stdout. */
public static void clearStdout() {
realPrint(stdout.toString());
stdout.delete(0, stdout.length());
}
/** Returns stdout as string. */
public static String getStdout() {
return stdout.toString();
}
public static void realPrintln(final String s) {
realOut.println(s);
}
public static void realPrint(final String s) {
realOut.print(s);
}
/** Print error and exit. */
public static void error(final String s) {
System.out.println(s);
System.exit(10);
}
public static void initTest() {
initTestCluster();
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
Tools.waitForSwing();
clearStdout();
}
/** Adds test cluster to the GUI. */
public static void initTestCluster() {
if (Tools.getGUIData() == null) {
if (CONNECT_LINBIT) {
lcmc.LCMC.main(new String[]{});
} else {
lcmc.LCMC.main(new String[]{"--no-upgrade-check"});
}
} else {
return;
}
Tools.setDebugLevel(-1);
if (CLUSTER) {
String username;
boolean useSudo;
if (TEST_USERNAME == null) {
username = "root";
useSudo = false;
} else {
username = TEST_USERNAME;
useSudo = true;
}
final Cluster cluster = new Cluster();
cluster.setName("test");
for (int i = 1; i <= NUMBER_OF_HOSTS; i++) {
String hostName;
if (TEST_HOSTNAME == null) {
hostName = "test" + i;
} else {
hostName = TEST_HOSTNAME + "-" + (char) ('a' - 1 + i);
}
final Host host = initHost(hostName, username, useSudo);
HOSTS.add(host);
host.setCluster(cluster);
cluster.addHost(host);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
}
for (int i = 0; i <= getFactor() / 100; i++) {
for (final Host host : HOSTS) {
host.disconnect();
}
cluster.connect(null, true, i);
for (final Host host : HOSTS) {
final boolean r = waitForCondition(
new Condition() {
@Override
public boolean passed() {
return host.isConnected();
}
}, 300, 20000);
if (!r) {
error("could not establish connection to "
+ host.getName());
}
}
}
if (!Tools.getConfigData().existsCluster(cluster)) {
Tools.getConfigData().addClusterToClusters(cluster);
- Tools.getGUIData().addClusterTab(cluster);
+ Tools.invokeAndWait(new Runnable() {
+ public void run() {
+ Tools.getGUIData().addClusterTab(cluster);
+ }
+ });
}
Tools.getGUIData().getEmptyBrowser().addClusterBox(cluster);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
Tools.getGUIData().refreshClustersPanel();
Tools.getGUIData().expandTerminalSplitPane(1);
cluster.getClusterTab().addClusterView();
cluster.getClusterTab().requestFocus();
Tools.getGUIData().checkAddClusterButtons();
for (final Host host : HOSTS) {
host.waitForServerStatusLatch();
}
}
}
private static Host initHost(final String hostName,
final String username,
final boolean useSudo) {
final Host host = new Host();
host.setHostnameEntered(hostName);
host.setUsername(username);
host.setSSHPort("22");
host.setUseSudo(useSudo);
if (!Tools.getConfigData().existsHost(host)) {
Tools.getConfigData().addHostToHosts(host);
Tools.getGUIData().setTerminalPanel(new TerminalPanel(host));
}
String ip;
InetAddress[] addresses;
try {
addresses = InetAddress.getAllByName(hostName);
ip = addresses[0].getHostAddress();
if (ip != null) {
host.setHostname(InetAddress.getByName(ip).getHostName());
}
} catch (UnknownHostException e) {
error("cannot resolve: " + hostName);
return null;
}
host.getSSH().setPasswords(ID_DSA_KEY, ID_RSA_KEY, PASSWORD);
host.setIp(ip);
host.setIps(0, new String[]{ip});
return host;
}
/** Returns test hosts. */
public static List<Host> getHosts() {
return HOSTS;
}
/** Returns factor for number of iteractions. */
public static int getFactor() {
if (FACTOR != null && Tools.isNumber(FACTOR)) {
return Integer.parseInt(FACTOR);
}
return 1;
}
public static List<String> getTest1Classes(final String path) {
final List<String> fileList = new ArrayList<String>();
if (path == null) {
return fileList;
}
final File dir = new File(path);
if (!dir.isDirectory()) {
if (path.endsWith("Test1.class")) {
fileList.add(path);
}
return fileList;
}
for (final String fn : dir.list()) {
if (fn.charAt(0) != '.') {
fileList.addAll(getTest1Classes(path + "/" + fn));
}
}
return fileList;
}
@SuppressWarnings("unchecked")
public static void main(final String[] args) {
final TestSuite suite = new TestSuite();
for (final String classes : new String[]{"build/classes",
"target/test-classes"}) {
final int startPos = classes.length() + 1;
for (final String c : getTest1Classes(classes)) {
final String className =
c.substring(startPos, c.length() - 6).replaceAll("[/\\\\]", ".");
try {
suite.addTestSuite((Class<? extends TestCase>)
TestCase.class.getClassLoader().loadClass(className));
} catch (java.lang.ClassNotFoundException e) {
error("unusable class: " + className);
}
}
}
junit.textui.TestRunner.run(suite);
System.exit(0);
}
/** Specify a condition to be passed to the waitForCondition function. */
public interface Condition {
/** returns true if condition is true. */
boolean passed();
}
/**
* Wait for condition 'timeout' seconds, check every 'interval' second.
* Return false if it ran to the timeout.
*/
public static boolean waitForCondition(final Condition condition,
final int interval,
final int timeout) {
int timeoutLeft = timeout;
while (!condition.passed() && timeout >= 0) {
Tools.sleep(interval);
timeoutLeft -= interval;
}
return timeoutLeft >= 0;
}
/** Check that not even one value is null. */
public static <T> boolean noValueIsNull(final Map<T, T> map) {
for (final T key : map.keySet()) {
if (key == null) {
return false;
}
if (map.get(key) == null) {
return false;
}
}
return true;
}
/** Check that not even one value is null. */
public static <T> boolean noValueIsNull(final List<T> list) {
for (final T o : list) {
if (o == null) {
return false;
}
}
return true;
}
/** Check that not even one value is null. */
public static <T> boolean noValueIsNull(final Set<T> list) {
for (final T o : list) {
if (o == null) {
return false;
}
}
return true;
}
/** Check that not even one value is null. */
public static <T> boolean noValueIsNull(final T[] strings) {
for (final T s : strings) {
if (s == null) {
return false;
}
}
return true;
}
}
| true | true | public static void initTestCluster() {
if (Tools.getGUIData() == null) {
if (CONNECT_LINBIT) {
lcmc.LCMC.main(new String[]{});
} else {
lcmc.LCMC.main(new String[]{"--no-upgrade-check"});
}
} else {
return;
}
Tools.setDebugLevel(-1);
if (CLUSTER) {
String username;
boolean useSudo;
if (TEST_USERNAME == null) {
username = "root";
useSudo = false;
} else {
username = TEST_USERNAME;
useSudo = true;
}
final Cluster cluster = new Cluster();
cluster.setName("test");
for (int i = 1; i <= NUMBER_OF_HOSTS; i++) {
String hostName;
if (TEST_HOSTNAME == null) {
hostName = "test" + i;
} else {
hostName = TEST_HOSTNAME + "-" + (char) ('a' - 1 + i);
}
final Host host = initHost(hostName, username, useSudo);
HOSTS.add(host);
host.setCluster(cluster);
cluster.addHost(host);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
}
for (int i = 0; i <= getFactor() / 100; i++) {
for (final Host host : HOSTS) {
host.disconnect();
}
cluster.connect(null, true, i);
for (final Host host : HOSTS) {
final boolean r = waitForCondition(
new Condition() {
@Override
public boolean passed() {
return host.isConnected();
}
}, 300, 20000);
if (!r) {
error("could not establish connection to "
+ host.getName());
}
}
}
if (!Tools.getConfigData().existsCluster(cluster)) {
Tools.getConfigData().addClusterToClusters(cluster);
Tools.getGUIData().addClusterTab(cluster);
}
Tools.getGUIData().getEmptyBrowser().addClusterBox(cluster);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
Tools.getGUIData().refreshClustersPanel();
Tools.getGUIData().expandTerminalSplitPane(1);
cluster.getClusterTab().addClusterView();
cluster.getClusterTab().requestFocus();
Tools.getGUIData().checkAddClusterButtons();
for (final Host host : HOSTS) {
host.waitForServerStatusLatch();
}
}
}
| public static void initTestCluster() {
if (Tools.getGUIData() == null) {
if (CONNECT_LINBIT) {
lcmc.LCMC.main(new String[]{});
} else {
lcmc.LCMC.main(new String[]{"--no-upgrade-check"});
}
} else {
return;
}
Tools.setDebugLevel(-1);
if (CLUSTER) {
String username;
boolean useSudo;
if (TEST_USERNAME == null) {
username = "root";
useSudo = false;
} else {
username = TEST_USERNAME;
useSudo = true;
}
final Cluster cluster = new Cluster();
cluster.setName("test");
for (int i = 1; i <= NUMBER_OF_HOSTS; i++) {
String hostName;
if (TEST_HOSTNAME == null) {
hostName = "test" + i;
} else {
hostName = TEST_HOSTNAME + "-" + (char) ('a' - 1 + i);
}
final Host host = initHost(hostName, username, useSudo);
HOSTS.add(host);
host.setCluster(cluster);
cluster.addHost(host);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
}
for (int i = 0; i <= getFactor() / 100; i++) {
for (final Host host : HOSTS) {
host.disconnect();
}
cluster.connect(null, true, i);
for (final Host host : HOSTS) {
final boolean r = waitForCondition(
new Condition() {
@Override
public boolean passed() {
return host.isConnected();
}
}, 300, 20000);
if (!r) {
error("could not establish connection to "
+ host.getName());
}
}
}
if (!Tools.getConfigData().existsCluster(cluster)) {
Tools.getConfigData().addClusterToClusters(cluster);
Tools.invokeAndWait(new Runnable() {
public void run() {
Tools.getGUIData().addClusterTab(cluster);
}
});
}
Tools.getGUIData().getEmptyBrowser().addClusterBox(cluster);
final String saveFile = Tools.getConfigData().getSaveFile();
Tools.save(saveFile, false);
Tools.getGUIData().refreshClustersPanel();
Tools.getGUIData().expandTerminalSplitPane(1);
cluster.getClusterTab().addClusterView();
cluster.getClusterTab().requestFocus();
Tools.getGUIData().checkAddClusterButtons();
for (final Host host : HOSTS) {
host.waitForServerStatusLatch();
}
}
}
|
diff --git a/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/BasePhraseAnalyzer.java b/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/BasePhraseAnalyzer.java
index 23fbd34a..251b7bac 100644
--- a/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/BasePhraseAnalyzer.java
+++ b/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/BasePhraseAnalyzer.java
@@ -1,278 +1,274 @@
package org.wikapidia.phrases;
import com.google.code.externalsorting.ExternalSort;
import org.wikapidia.core.dao.DaoException;
import org.wikapidia.core.dao.LocalPageDao;
import org.wikapidia.core.lang.Language;
import org.wikapidia.core.lang.LanguageSet;
import org.wikapidia.core.model.LocalPage;
import org.wikapidia.core.model.NameSpace;
import org.wikapidia.core.model.Title;
import org.wikapidia.core.model.UniversalPage;
import org.wikapidia.utils.WpIOUtils;
import org.wikapidia.utils.WpStringUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.*;
import java.util.logging.Logger;
/**
* Base implementation of a phrase analyzer.
* Concrete implementations extending this class need only implement a getCorpus() method.
*/
public abstract class BasePhraseAnalyzer implements PhraseAnalyzer {
private static final Logger LOG = Logger.getLogger(PhraseAnalyzer.class.getName());
/**
* An entry in the phrase corpus.
* Some implementations may have a local id.
* Others will only have a title.
*/
public static class Entry {
Language language;
int localId = -1;
String title = null;
String phrase;
int count;
public Entry(Language language, int localId, String phrase, int count) {
this.language = language;
this.localId = localId;
this.phrase = phrase;
this.count = count;
}
public Entry(Language language, String title, String phrase, int count) {
this.language = language;
this.title = title;
this.phrase = phrase;
this.count = count;
}
}
protected PhraseAnalyzerDao phraseDao;
protected LocalPageDao pageDao;
public BasePhraseAnalyzer(PhraseAnalyzerDao phraseDao, LocalPageDao pageDao) {
this.phraseDao = phraseDao;
this.pageDao = pageDao;
}
/**
* Concrete implementations must override this method to determine what phrases
* are stored.
*
* @return
* @throws IOException
* @throws DaoException
*/
protected abstract Iterable<Entry> getCorpus(LanguageSet langs) throws IOException, DaoException;
/**
* Loads a specific corpus into the dao.
*
* @throws DaoException
* @throws IOException
*/
@Override
public void loadCorpus(LanguageSet langs, PrunedCounts.Pruner<String> pagePruner, PrunedCounts.Pruner<Integer> phrasePruner) throws DaoException, IOException {
// create temp files for storing corpus entries by phrase and local id.
// these will ultimately be sorted to group together records with the same phrase / id.
File byWpIdFile = File.createTempFile("wp_phrases_by_id", "txt");
byWpIdFile.deleteOnExit();
BufferedWriter byWpId = WpIOUtils.openWriter(byWpIdFile);
File byPhraseFile = File.createTempFile("wp_phrases_by_phrase", "txt");
byPhraseFile.deleteOnExit();
BufferedWriter byPhrase = WpIOUtils.openWriter(byPhraseFile);
// Iterate over each entry in the corpus.
// Throws away entries in languages we don't care about.
// Resolve titles to ids if necessary.
// Write entries to the by phrase / id files.
long numEntries = 0;
long numEntriesRetained = 0;
for (Entry e : getCorpus(langs)) {
if (++numEntries % 100000 == 0) {
double p = 100.0 * numEntriesRetained / numEntries;
LOG.info("processing entry: " + numEntries +
", retained " + numEntriesRetained +
"(" + new DecimalFormat("#.#").format(p) + "%)");
}
if (!langs.containsLanguage(e.language)) {
continue;
}
if (e.title != null && e.localId < 0) {
- LocalPage lp = pageDao.getByTitle(e.language,
- new Title(e.title, e.language),
- NameSpace.ARTICLE);
- if (lp != null) {
- e.localId = lp.getLocalId();
- }
+ int localId = pageDao.getIdByTitle(e.title, e.language,NameSpace.ARTICLE);
+ e.localId = (localId <= 0) ? -1 : localId;
}
if (e.localId < 0) {
continue;
}
numEntriesRetained++;
e.phrase = e.phrase.replace("\n", " ").replace("\t", " ");
// phrase is last because it may contain tabs.
String line = e.language.getLangCode() + "\t" + e.localId + "\t" + e.count + "\t" + e.phrase + "\n";
byPhrase.write(e.language.getLangCode() + ":" + WpStringUtils.normalize(e.phrase) + "\t" + line);
byWpId.write(e.language.getLangCode() + ":" + e.localId + "\t" + line);
}
byWpId.close();
byPhrase.close();
// sort phrases by phrase / id and load them
sortInPlace(byWpIdFile);
loadFromFile(RecordType.PAGES, byWpIdFile, pagePruner);
sortInPlace(byPhraseFile);
loadFromFile(RecordType.PHRASES, byPhraseFile, phrasePruner);
}
private static enum RecordType {
PAGES, PHRASES
}
protected void loadFromFile(RecordType ltype, File input, PrunedCounts.Pruner pruner) throws IOException, DaoException {
BufferedReader reader = WpIOUtils.openBufferedReader(input);
String lastKey = null;
List<Entry> buffer = new ArrayList<Entry>();
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
String tokens[] = line.split("\t", 5);
if (tokens.length != 5) {
LOG.warning("invalid line in file " + input + ": " + line);
continue;
}
// if new id, write out buffer and clear it
if (lastKey != null && !tokens[0].equals(lastKey)) {
if (ltype == RecordType.PAGES) {
writePage(buffer, pruner);
} else {
writePhrase(buffer, pruner);
}
buffer.clear();
}
Entry e = new Entry(
Language.getByLangCode(tokens[1]),
new Integer(tokens[2]),
tokens[4],
new Integer(tokens[3])
);
buffer.add(e);
lastKey = tokens[0];
}
if (ltype == RecordType.PAGES) {
writePage(buffer, pruner);
} else {
writePhrase(buffer, pruner);
}
}
protected void writePage(List<Entry> pageCounts, PrunedCounts.Pruner pruner) throws DaoException {
if (pageCounts.isEmpty()) {
return;
}
Language lang = pageCounts.get(0).language;
int wpId = pageCounts.get(0).localId;
Map<String, Integer> counts = new HashMap<String, Integer>();
for (Entry e : pageCounts) {
if (e.localId != wpId) throw new IllegalStateException();
if (e.language != lang) throw new IllegalStateException();
if (counts.containsKey(e.phrase)) {
counts.put(e.phrase, counts.get(e.phrase) + e.count);
} else {
counts.put(e.phrase, e.count);
}
}
PrunedCounts<String> pruned = pruner.prune(counts);
if (pruned != null) {
phraseDao.savePageCounts(lang, wpId, pruned);
}
}
protected void writePhrase(List<Entry> pageCounts, PrunedCounts.Pruner pruner) throws DaoException {
if (pageCounts.isEmpty()) {
return;
}
Language lang = pageCounts.get(0).language;
String phrase = WpStringUtils.normalize(pageCounts.get(0).phrase);
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (Entry e : pageCounts) {
if (!WpStringUtils.normalize(e.phrase).equals(phrase)) {
LOG.warning("disagreement between phrases " + phrase + " and " + e.phrase);
}
if (e.language != lang) {
LOG.warning("disagreement between languages " + lang+ " and " + e.language);
}
if (counts.containsKey(e.localId)) {
counts.put(e.localId, counts.get(e.localId) + e.count);
} else {
counts.put(e.localId, e.count);
}
}
PrunedCounts<Integer> pruned = pruner.prune(counts);
if (pruned != null) {
phraseDao.savePhraseCounts(lang, phrase, pruned);
}
}
private void sortInPlace(File file) throws IOException {
Comparator<String> comparator = new Comparator<String>() {
public int compare(String r1, String r2){
return r1.compareTo(r2);}};
List<File> l = ExternalSort.sortInBatch(file, comparator, 1024, Charset.forName("utf-8"), null, false);
ExternalSort.mergeSortedFiles(l, file, comparator, Charset.forName("utf-8"));
}
@Override
public LinkedHashMap<String, Float> describeLocal(Language language, LocalPage page, int maxPhrases) throws DaoException {
LinkedHashMap<String, Float> result = new LinkedHashMap<String, Float>();
PrunedCounts<String> counts = phraseDao.getPageCounts(language, page.getLocalId(), maxPhrases);
if (counts == null) {
return null;
}
for (String phrase : counts.keySet()) {
result.put(phrase, (float)1.0 * counts.get(phrase) / counts.getTotal());
if (counts.size() >= maxPhrases) {
break;
}
}
return result;
}
@Override
public LinkedHashMap<LocalPage, Float> resolveLocal(Language language, String phrase, int maxPages) throws DaoException {
LinkedHashMap<LocalPage, Float> result = new LinkedHashMap<LocalPage, Float>();
PrunedCounts<Integer> counts = phraseDao.getPhraseCounts(language, phrase, maxPages);
if (counts == null) {
return null;
}
for (Integer wpId : counts.keySet()) {
result.put(pageDao.getById(language, wpId),
(float)1.0 * counts.get(wpId) / counts.getTotal());
if (counts.size() >= maxPages) {
break;
}
}
return result;
}
@Override
public LinkedHashMap<String, Float> describeUniversal(Language language, UniversalPage page, int maxPhrases) {
throw new UnsupportedOperationException();
}
@Override
public LinkedHashMap<UniversalPage, Float> resolveUniversal(Language language, String phrase, int algorithmId, int maxPages) {
throw new UnsupportedOperationException();
}
}
| true | true | public void loadCorpus(LanguageSet langs, PrunedCounts.Pruner<String> pagePruner, PrunedCounts.Pruner<Integer> phrasePruner) throws DaoException, IOException {
// create temp files for storing corpus entries by phrase and local id.
// these will ultimately be sorted to group together records with the same phrase / id.
File byWpIdFile = File.createTempFile("wp_phrases_by_id", "txt");
byWpIdFile.deleteOnExit();
BufferedWriter byWpId = WpIOUtils.openWriter(byWpIdFile);
File byPhraseFile = File.createTempFile("wp_phrases_by_phrase", "txt");
byPhraseFile.deleteOnExit();
BufferedWriter byPhrase = WpIOUtils.openWriter(byPhraseFile);
// Iterate over each entry in the corpus.
// Throws away entries in languages we don't care about.
// Resolve titles to ids if necessary.
// Write entries to the by phrase / id files.
long numEntries = 0;
long numEntriesRetained = 0;
for (Entry e : getCorpus(langs)) {
if (++numEntries % 100000 == 0) {
double p = 100.0 * numEntriesRetained / numEntries;
LOG.info("processing entry: " + numEntries +
", retained " + numEntriesRetained +
"(" + new DecimalFormat("#.#").format(p) + "%)");
}
if (!langs.containsLanguage(e.language)) {
continue;
}
if (e.title != null && e.localId < 0) {
LocalPage lp = pageDao.getByTitle(e.language,
new Title(e.title, e.language),
NameSpace.ARTICLE);
if (lp != null) {
e.localId = lp.getLocalId();
}
}
if (e.localId < 0) {
continue;
}
numEntriesRetained++;
e.phrase = e.phrase.replace("\n", " ").replace("\t", " ");
// phrase is last because it may contain tabs.
String line = e.language.getLangCode() + "\t" + e.localId + "\t" + e.count + "\t" + e.phrase + "\n";
byPhrase.write(e.language.getLangCode() + ":" + WpStringUtils.normalize(e.phrase) + "\t" + line);
byWpId.write(e.language.getLangCode() + ":" + e.localId + "\t" + line);
}
byWpId.close();
byPhrase.close();
// sort phrases by phrase / id and load them
sortInPlace(byWpIdFile);
loadFromFile(RecordType.PAGES, byWpIdFile, pagePruner);
sortInPlace(byPhraseFile);
loadFromFile(RecordType.PHRASES, byPhraseFile, phrasePruner);
}
| public void loadCorpus(LanguageSet langs, PrunedCounts.Pruner<String> pagePruner, PrunedCounts.Pruner<Integer> phrasePruner) throws DaoException, IOException {
// create temp files for storing corpus entries by phrase and local id.
// these will ultimately be sorted to group together records with the same phrase / id.
File byWpIdFile = File.createTempFile("wp_phrases_by_id", "txt");
byWpIdFile.deleteOnExit();
BufferedWriter byWpId = WpIOUtils.openWriter(byWpIdFile);
File byPhraseFile = File.createTempFile("wp_phrases_by_phrase", "txt");
byPhraseFile.deleteOnExit();
BufferedWriter byPhrase = WpIOUtils.openWriter(byPhraseFile);
// Iterate over each entry in the corpus.
// Throws away entries in languages we don't care about.
// Resolve titles to ids if necessary.
// Write entries to the by phrase / id files.
long numEntries = 0;
long numEntriesRetained = 0;
for (Entry e : getCorpus(langs)) {
if (++numEntries % 100000 == 0) {
double p = 100.0 * numEntriesRetained / numEntries;
LOG.info("processing entry: " + numEntries +
", retained " + numEntriesRetained +
"(" + new DecimalFormat("#.#").format(p) + "%)");
}
if (!langs.containsLanguage(e.language)) {
continue;
}
if (e.title != null && e.localId < 0) {
int localId = pageDao.getIdByTitle(e.title, e.language,NameSpace.ARTICLE);
e.localId = (localId <= 0) ? -1 : localId;
}
if (e.localId < 0) {
continue;
}
numEntriesRetained++;
e.phrase = e.phrase.replace("\n", " ").replace("\t", " ");
// phrase is last because it may contain tabs.
String line = e.language.getLangCode() + "\t" + e.localId + "\t" + e.count + "\t" + e.phrase + "\n";
byPhrase.write(e.language.getLangCode() + ":" + WpStringUtils.normalize(e.phrase) + "\t" + line);
byWpId.write(e.language.getLangCode() + ":" + e.localId + "\t" + line);
}
byWpId.close();
byPhrase.close();
// sort phrases by phrase / id and load them
sortInPlace(byWpIdFile);
loadFromFile(RecordType.PAGES, byWpIdFile, pagePruner);
sortInPlace(byPhraseFile);
loadFromFile(RecordType.PHRASES, byPhraseFile, phrasePruner);
}
|
diff --git a/src/npcs/actions/AAsk.java b/src/npcs/actions/AAsk.java
index e8cfe20..1040ae6 100644
--- a/src/npcs/actions/AAsk.java
+++ b/src/npcs/actions/AAsk.java
@@ -1,93 +1,89 @@
package npcs.actions;
import fap_java.NPC;
public class AAsk implements Action {
private String message;
private String yesOption;
private String noOption;
private boolean choice;
private int iterator = 0;
private Action failAction;
public AAsk(String message, String yes, String no, Action failAction) {
super();
this.message = message;
this.yesOption = yes;
this.noOption = no;
choice = true;
this.failAction = failAction;
}
public void execute(NPC whoLaunches) {
if(iterator == 0){
System.out.println(message);
iterator++;
whoLaunches.setIterator(whoLaunches.getIterator()-1);
}
else{
System.out.println("You chose : "+choice);
if(choice){
//Loop
if(whoLaunches != null && whoLaunches.getIterator() <= whoLaunches.getActions().size()){
+ this.reinit();
whoLaunches.execute();
}
}
else{
//End NPC
whoLaunches.setIterator(whoLaunches.getActions().size()+2);
failAction.execute(whoLaunches);
}
- //Loop
- if(whoLaunches != null && whoLaunches.getIterator() <= whoLaunches.getActions().size()){
- this.iterator = 0;
- whoLaunches.execute();
- }
}
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setYesOption(String yesOption) {
this.yesOption = yesOption;
}
public String getYesOption() {
return yesOption;
}
public void setNoOption(String noOption) {
this.noOption = noOption;
}
public String getNoOption() {
return noOption;
}
public void setIterator(int iterator) {
this.iterator = iterator;
}
public int getIterator() {
return iterator;
}
public void setChoice(boolean choice) {
this.choice = choice;
}
public boolean isChoice() {
return choice;
}
public void reinit() {
iterator = 0;
failAction.reinit();
}
}
| false | true | public void execute(NPC whoLaunches) {
if(iterator == 0){
System.out.println(message);
iterator++;
whoLaunches.setIterator(whoLaunches.getIterator()-1);
}
else{
System.out.println("You chose : "+choice);
if(choice){
//Loop
if(whoLaunches != null && whoLaunches.getIterator() <= whoLaunches.getActions().size()){
whoLaunches.execute();
}
}
else{
//End NPC
whoLaunches.setIterator(whoLaunches.getActions().size()+2);
failAction.execute(whoLaunches);
}
//Loop
if(whoLaunches != null && whoLaunches.getIterator() <= whoLaunches.getActions().size()){
this.iterator = 0;
whoLaunches.execute();
}
}
}
| public void execute(NPC whoLaunches) {
if(iterator == 0){
System.out.println(message);
iterator++;
whoLaunches.setIterator(whoLaunches.getIterator()-1);
}
else{
System.out.println("You chose : "+choice);
if(choice){
//Loop
if(whoLaunches != null && whoLaunches.getIterator() <= whoLaunches.getActions().size()){
this.reinit();
whoLaunches.execute();
}
}
else{
//End NPC
whoLaunches.setIterator(whoLaunches.getActions().size()+2);
failAction.execute(whoLaunches);
}
}
}
|
diff --git a/src/de/lemo/dms/processing/QUserInformation.java b/src/de/lemo/dms/processing/QUserInformation.java
index f2a54759..8187a3c7 100644
--- a/src/de/lemo/dms/processing/QUserInformation.java
+++ b/src/de/lemo/dms/processing/QUserInformation.java
@@ -1,76 +1,82 @@
package de.lemo.dms.processing;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import de.lemo.dms.core.ServerConfigurationHardCoded;
import de.lemo.dms.db.EQueryType;
import de.lemo.dms.db.IDBHandler;
import de.lemo.dms.db.miningDBclass.CourseMining;
import de.lemo.dms.processing.parameter.Parameter;
import de.lemo.dms.processing.parameter.ParameterMetaData;
import de.lemo.dms.processing.resulttype.CourseObject;
import de.lemo.dms.processing.resulttype.ResultList;
@Path("userinformation")
public class QUserInformation extends Question{
@Override
protected List<ParameterMetaData<?>> createParamMetaData() {
// TODO Auto-generated method stub
List<ParameterMetaData<?>> parameters = new LinkedList<ParameterMetaData<?>>();
Collections.<Parameter<?>> addAll( parameters,
Parameter.create("user_id","User","ID of the user."),
Parameter.create("course_count","Course count","Number of courses that should be displayed."),
Parameter.create("course_offset","Course offset","")
);
return parameters;
}
@GET
public ResultList getCoursesByUser(@QueryParam("user_id") Long id, @QueryParam("course_count") Long count,
@QueryParam("course_offset") Long offset) {
ArrayList<CourseObject> courses = new ArrayList<CourseObject>();
//Set up db-connection
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
dbHandler.getConnection(ServerConfigurationHardCoded.getInstance().getMiningDBConfig());
ArrayList<Long> cu = (ArrayList<Long>)dbHandler.performQuery(EQueryType.SQL, "Select course_id from course_user where user_id=" + id);
String query = "";
for(int i = 0; i < cu.size(); i++)
{
if(i==0)
query += "("+cu.get(i);
else
query += ","+cu.get(i);
if(i == cu.size()-1)
query += ")";
}
if(cu.size() > 0 )
{
ArrayList<CourseMining> ci = (ArrayList<CourseMining>) dbHandler.performQuery(EQueryType.HQL, "from CourseMining where id in " + query);
for(int i = 0; i < ci.size(); i++)
{
- ArrayList<?> parti = (ArrayList<?>) dbHandler.performQuery(EQueryType.SQL, "Select count(DISTINCT user_id) from course_user where course_id="+ci.get(i).getId());
- ArrayList<?> latest = (ArrayList<?>) dbHandler.performQuery(EQueryType.SQL, "Select max(timestamp) from resource_log where course_id="+ci.get(i).getId());
- CourseObject co = new CourseObject(ci.get(i).getId(), ci.get(i).getShortname(), ci.get(i).getTitle(), ((BigInteger)parti.get(0)).longValue(), ((BigInteger)latest.get(0)).longValue() );
+ ArrayList<Long> parti = (ArrayList<Long>) dbHandler.performQuery(EQueryType.HQL, "Select count(DISTINCT user) from CourseUserMining where course="+ci.get(i).getId());
+ ArrayList<Long> latest = (ArrayList<Long>) dbHandler.performQuery(EQueryType.HQL, "Select max(timestamp) FROM ResourceLogMining x WHERE x.course="+ci.get(i).getId());
+ Long c_pa = 0L;
+ if(parti.size() > 0 && parti.get(0) != null)
+ c_pa = parti.get(0);
+ Long c_la = 0L;
+ if(latest.size() > 0 && latest.get(0) != null)
+ c_la = latest.get(0);
+ CourseObject co = new CourseObject(ci.get(i).getId(), ci.get(i).getShortname(), ci.get(i).getTitle(), c_pa, c_la );
courses.add(co);
}
}
return new ResultList(courses);
}
}
| true | true | public ResultList getCoursesByUser(@QueryParam("user_id") Long id, @QueryParam("course_count") Long count,
@QueryParam("course_offset") Long offset) {
ArrayList<CourseObject> courses = new ArrayList<CourseObject>();
//Set up db-connection
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
dbHandler.getConnection(ServerConfigurationHardCoded.getInstance().getMiningDBConfig());
ArrayList<Long> cu = (ArrayList<Long>)dbHandler.performQuery(EQueryType.SQL, "Select course_id from course_user where user_id=" + id);
String query = "";
for(int i = 0; i < cu.size(); i++)
{
if(i==0)
query += "("+cu.get(i);
else
query += ","+cu.get(i);
if(i == cu.size()-1)
query += ")";
}
if(cu.size() > 0 )
{
ArrayList<CourseMining> ci = (ArrayList<CourseMining>) dbHandler.performQuery(EQueryType.HQL, "from CourseMining where id in " + query);
for(int i = 0; i < ci.size(); i++)
{
ArrayList<?> parti = (ArrayList<?>) dbHandler.performQuery(EQueryType.SQL, "Select count(DISTINCT user_id) from course_user where course_id="+ci.get(i).getId());
ArrayList<?> latest = (ArrayList<?>) dbHandler.performQuery(EQueryType.SQL, "Select max(timestamp) from resource_log where course_id="+ci.get(i).getId());
CourseObject co = new CourseObject(ci.get(i).getId(), ci.get(i).getShortname(), ci.get(i).getTitle(), ((BigInteger)parti.get(0)).longValue(), ((BigInteger)latest.get(0)).longValue() );
courses.add(co);
}
}
return new ResultList(courses);
}
| public ResultList getCoursesByUser(@QueryParam("user_id") Long id, @QueryParam("course_count") Long count,
@QueryParam("course_offset") Long offset) {
ArrayList<CourseObject> courses = new ArrayList<CourseObject>();
//Set up db-connection
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
dbHandler.getConnection(ServerConfigurationHardCoded.getInstance().getMiningDBConfig());
ArrayList<Long> cu = (ArrayList<Long>)dbHandler.performQuery(EQueryType.SQL, "Select course_id from course_user where user_id=" + id);
String query = "";
for(int i = 0; i < cu.size(); i++)
{
if(i==0)
query += "("+cu.get(i);
else
query += ","+cu.get(i);
if(i == cu.size()-1)
query += ")";
}
if(cu.size() > 0 )
{
ArrayList<CourseMining> ci = (ArrayList<CourseMining>) dbHandler.performQuery(EQueryType.HQL, "from CourseMining where id in " + query);
for(int i = 0; i < ci.size(); i++)
{
ArrayList<Long> parti = (ArrayList<Long>) dbHandler.performQuery(EQueryType.HQL, "Select count(DISTINCT user) from CourseUserMining where course="+ci.get(i).getId());
ArrayList<Long> latest = (ArrayList<Long>) dbHandler.performQuery(EQueryType.HQL, "Select max(timestamp) FROM ResourceLogMining x WHERE x.course="+ci.get(i).getId());
Long c_pa = 0L;
if(parti.size() > 0 && parti.get(0) != null)
c_pa = parti.get(0);
Long c_la = 0L;
if(latest.size() > 0 && latest.get(0) != null)
c_la = latest.get(0);
CourseObject co = new CourseObject(ci.get(i).getId(), ci.get(i).getShortname(), ci.get(i).getTitle(), c_pa, c_la );
courses.add(co);
}
}
return new ResultList(courses);
}
|
diff --git a/src/com/android/settings/bluetooth/BluetoothSettings.java b/src/com/android/settings/bluetooth/BluetoothSettings.java
old mode 100644
new mode 100755
index 9f56f32ac..e18e48a25
--- a/src/com/android/settings/bluetooth/BluetoothSettings.java
+++ b/src/com/android/settings/bluetooth/BluetoothSettings.java
@@ -1,374 +1,375 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.bluetooth;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import com.android.settings.ProgressCategory;
import com.android.settings.R;
/**
* BluetoothSettings is the Settings screen for Bluetooth configuration and
* connection management.
*/
public final class BluetoothSettings extends DeviceListPreferenceFragment {
private static final String TAG = "BluetoothSettings";
private static final int MENU_ID_SCAN = Menu.FIRST;
private static final int MENU_ID_RENAME_DEVICE = Menu.FIRST + 1;
private static final int MENU_ID_VISIBILITY_TIMEOUT = Menu.FIRST + 2;
private static final int MENU_ID_SHOW_RECEIVED = Menu.FIRST + 3;
/* Private intent to show the list of received files */
private static final String BTOPP_ACTION_OPEN_RECEIVED_FILES =
"android.btopp.intent.action.OPEN_RECEIVED_FILES";
private BluetoothEnabler mBluetoothEnabler;
private BluetoothDiscoverableEnabler mDiscoverableEnabler;
private PreferenceGroup mPairedDevicesCategory;
private PreferenceGroup mAvailableDevicesCategory;
private boolean mAvailableDevicesCategoryIsPresent;
private boolean mActivityStarted;
private TextView mEmptyView;
private final IntentFilter mIntentFilter;
// accessed from inner class (not private to avoid thunks)
Preference mMyDevicePreference;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED)) {
updateDeviceName();
}
}
private void updateDeviceName() {
if (mLocalAdapter.isEnabled() && mMyDevicePreference != null) {
mMyDevicePreference.setTitle(mLocalAdapter.getName());
}
}
};
public BluetoothSettings() {
mIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
mActivityStarted = true;
super.onActivityCreated(savedInstanceState);
mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
getListView().setEmptyView(mEmptyView);
}
@Override
void addPreferencesForActivity() {
addPreferencesFromResource(R.xml.bluetooth_settings);
Activity activity = getActivity();
Switch actionBarSwitch = new Switch(activity);
if (activity instanceof PreferenceActivity) {
PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
final int padding = activity.getResources().getDimensionPixelSize(
R.dimen.action_bar_switch_padding);
actionBarSwitch.setPadding(0, 0, padding, 0);
activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM);
activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.RIGHT));
}
}
mBluetoothEnabler = new BluetoothEnabler(activity, actionBarSwitch);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
// resume BluetoothEnabler before calling super.onResume() so we don't get
// any onDeviceAdded() callbacks before setting up view in updateContent()
mBluetoothEnabler.resume();
super.onResume();
if (mDiscoverableEnabler != null) {
mDiscoverableEnabler.resume();
}
getActivity().registerReceiver(mReceiver, mIntentFilter);
updateContent(mLocalAdapter.getBluetoothState(), mActivityStarted);
}
@Override
public void onPause() {
super.onPause();
mBluetoothEnabler.pause();
getActivity().unregisterReceiver(mReceiver);
if (mDiscoverableEnabler != null) {
mDiscoverableEnabler.pause();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
boolean bluetoothIsEnabled = mLocalAdapter.getBluetoothState() == BluetoothAdapter.STATE_ON;
boolean isDiscovering = mLocalAdapter.isDiscovering();
int textId = isDiscovering ? R.string.bluetooth_searching_for_devices :
R.string.bluetooth_search_for_devices;
menu.add(Menu.NONE, MENU_ID_SCAN, 0, textId)
.setEnabled(bluetoothIsEnabled && !isDiscovering)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(Menu.NONE, MENU_ID_RENAME_DEVICE, 0, R.string.bluetooth_rename_device)
.setEnabled(bluetoothIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
menu.add(Menu.NONE, MENU_ID_VISIBILITY_TIMEOUT, 0, R.string.bluetooth_visibility_timeout)
.setEnabled(bluetoothIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
menu.add(Menu.NONE, MENU_ID_SHOW_RECEIVED, 0, R.string.bluetooth_show_received_files)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ID_SCAN:
if (mLocalAdapter.getBluetoothState() == BluetoothAdapter.STATE_ON) {
startScanning();
}
return true;
case MENU_ID_RENAME_DEVICE:
new BluetoothNameDialogFragment().show(
getFragmentManager(), "rename device");
return true;
case MENU_ID_VISIBILITY_TIMEOUT:
new BluetoothVisibilityTimeoutFragment().show(
getFragmentManager(), "visibility timeout");
return true;
case MENU_ID_SHOW_RECEIVED:
Intent intent = new Intent(BTOPP_ACTION_OPEN_RECEIVED_FILES);
getActivity().sendBroadcast(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void startScanning() {
if (!mAvailableDevicesCategoryIsPresent) {
getPreferenceScreen().addPreference(mAvailableDevicesCategory);
}
mLocalAdapter.startScanning(true);
}
@Override
void onDevicePreferenceClick(BluetoothDevicePreference btPreference) {
mLocalAdapter.stopScanning();
super.onDevicePreferenceClick(btPreference);
}
private void addDeviceCategory(PreferenceGroup preferenceGroup, int titleId,
BluetoothDeviceFilter.Filter filter) {
preferenceGroup.setTitle(titleId);
getPreferenceScreen().addPreference(preferenceGroup);
setFilter(filter);
setDeviceListGroup(preferenceGroup);
addCachedDevices();
preferenceGroup.setEnabled(true);
}
private void updateContent(int bluetoothState, boolean scanState) {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
int messageId = 0;
switch (bluetoothState) {
case BluetoothAdapter.STATE_ON:
preferenceScreen.removeAll();
preferenceScreen.setOrderingAsAdded(true);
+ mDevicePreferenceMap.clear();
// This device
if (mMyDevicePreference == null) {
mMyDevicePreference = new Preference(getActivity());
}
mMyDevicePreference.setTitle(mLocalAdapter.getName());
if (getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {
mMyDevicePreference.setIcon(R.drawable.ic_bt_cellphone); // for phones
} else {
mMyDevicePreference.setIcon(R.drawable.ic_bt_laptop); // for tablets, etc.
}
mMyDevicePreference.setPersistent(false);
mMyDevicePreference.setEnabled(true);
preferenceScreen.addPreference(mMyDevicePreference);
if (mDiscoverableEnabler == null) {
mDiscoverableEnabler = new BluetoothDiscoverableEnabler(getActivity(),
mLocalAdapter, mMyDevicePreference);
mDiscoverableEnabler.resume();
LocalBluetoothManager.getInstance(getActivity()).setDiscoverableEnabler(
mDiscoverableEnabler);
}
// Paired devices category
if (mPairedDevicesCategory == null) {
mPairedDevicesCategory = new PreferenceCategory(getActivity());
} else {
mPairedDevicesCategory.removeAll();
}
addDeviceCategory(mPairedDevicesCategory,
R.string.bluetooth_preference_paired_devices,
BluetoothDeviceFilter.BONDED_DEVICE_FILTER);
int numberOfPairedDevices = mPairedDevicesCategory.getPreferenceCount();
mDiscoverableEnabler.setNumberOfPairedDevices(numberOfPairedDevices);
// Available devices category
if (mAvailableDevicesCategory == null) {
mAvailableDevicesCategory = new ProgressCategory(getActivity(), null);
} else {
mAvailableDevicesCategory.removeAll();
}
addDeviceCategory(mAvailableDevicesCategory,
R.string.bluetooth_preference_found_devices,
BluetoothDeviceFilter.UNBONDED_DEVICE_FILTER);
int numberOfAvailableDevices = mAvailableDevicesCategory.getPreferenceCount();
mAvailableDevicesCategoryIsPresent = true;
if (numberOfAvailableDevices == 0) {
preferenceScreen.removePreference(mAvailableDevicesCategory);
mAvailableDevicesCategoryIsPresent = false;
}
if (numberOfPairedDevices == 0) {
preferenceScreen.removePreference(mPairedDevicesCategory);
if (scanState == true) {
mActivityStarted = false;
startScanning();
} else {
if (!mAvailableDevicesCategoryIsPresent) {
getPreferenceScreen().addPreference(mAvailableDevicesCategory);
}
}
}
getActivity().invalidateOptionsMenu();
return; // not break
case BluetoothAdapter.STATE_TURNING_OFF:
messageId = R.string.bluetooth_turning_off;
break;
case BluetoothAdapter.STATE_OFF:
messageId = R.string.bluetooth_empty_list_bluetooth_off;
break;
case BluetoothAdapter.STATE_TURNING_ON:
messageId = R.string.bluetooth_turning_on;
break;
}
setDeviceListGroup(preferenceScreen);
removeAllDevices();
mEmptyView.setText(messageId);
getActivity().invalidateOptionsMenu();
}
@Override
public void onBluetoothStateChanged(int bluetoothState) {
super.onBluetoothStateChanged(bluetoothState);
updateContent(bluetoothState, true);
}
@Override
public void onScanningStateChanged(boolean started) {
super.onScanningStateChanged(started);
// Update options' enabled state
getActivity().invalidateOptionsMenu();
}
public void onDeviceBondStateChanged(CachedBluetoothDevice cachedDevice, int bondState) {
setDeviceListGroup(getPreferenceScreen());
removeAllDevices();
updateContent(mLocalAdapter.getBluetoothState(), false);
}
private final View.OnClickListener mDeviceProfilesListener = new View.OnClickListener() {
public void onClick(View v) {
// User clicked on advanced options icon for a device in the list
if (v.getTag() instanceof CachedBluetoothDevice) {
CachedBluetoothDevice device = (CachedBluetoothDevice) v.getTag();
Bundle args = new Bundle(1);
args.putParcelable(DeviceProfilesSettings.EXTRA_DEVICE, device.getDevice());
((PreferenceActivity) getActivity()).startPreferencePanel(
DeviceProfilesSettings.class.getName(), args,
R.string.bluetooth_device_advanced_title, null, null, 0);
} else {
Log.w(TAG, "onClick() called for other View: " + v); // TODO remove
}
}
};
/**
* Add a listener, which enables the advanced settings icon.
* @param preference the newly added preference
*/
@Override
void initDevicePreference(BluetoothDevicePreference preference) {
CachedBluetoothDevice cachedDevice = preference.getCachedDevice();
if (cachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
// Only paired device have an associated advanced settings screen
preference.setOnSettingsClickListener(mDeviceProfilesListener);
}
}
}
| true | true | private void updateContent(int bluetoothState, boolean scanState) {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
int messageId = 0;
switch (bluetoothState) {
case BluetoothAdapter.STATE_ON:
preferenceScreen.removeAll();
preferenceScreen.setOrderingAsAdded(true);
// This device
if (mMyDevicePreference == null) {
mMyDevicePreference = new Preference(getActivity());
}
mMyDevicePreference.setTitle(mLocalAdapter.getName());
if (getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {
mMyDevicePreference.setIcon(R.drawable.ic_bt_cellphone); // for phones
} else {
mMyDevicePreference.setIcon(R.drawable.ic_bt_laptop); // for tablets, etc.
}
mMyDevicePreference.setPersistent(false);
mMyDevicePreference.setEnabled(true);
preferenceScreen.addPreference(mMyDevicePreference);
if (mDiscoverableEnabler == null) {
mDiscoverableEnabler = new BluetoothDiscoverableEnabler(getActivity(),
mLocalAdapter, mMyDevicePreference);
mDiscoverableEnabler.resume();
LocalBluetoothManager.getInstance(getActivity()).setDiscoverableEnabler(
mDiscoverableEnabler);
}
// Paired devices category
if (mPairedDevicesCategory == null) {
mPairedDevicesCategory = new PreferenceCategory(getActivity());
} else {
mPairedDevicesCategory.removeAll();
}
addDeviceCategory(mPairedDevicesCategory,
R.string.bluetooth_preference_paired_devices,
BluetoothDeviceFilter.BONDED_DEVICE_FILTER);
int numberOfPairedDevices = mPairedDevicesCategory.getPreferenceCount();
mDiscoverableEnabler.setNumberOfPairedDevices(numberOfPairedDevices);
// Available devices category
if (mAvailableDevicesCategory == null) {
mAvailableDevicesCategory = new ProgressCategory(getActivity(), null);
} else {
mAvailableDevicesCategory.removeAll();
}
addDeviceCategory(mAvailableDevicesCategory,
R.string.bluetooth_preference_found_devices,
BluetoothDeviceFilter.UNBONDED_DEVICE_FILTER);
int numberOfAvailableDevices = mAvailableDevicesCategory.getPreferenceCount();
mAvailableDevicesCategoryIsPresent = true;
if (numberOfAvailableDevices == 0) {
preferenceScreen.removePreference(mAvailableDevicesCategory);
mAvailableDevicesCategoryIsPresent = false;
}
if (numberOfPairedDevices == 0) {
preferenceScreen.removePreference(mPairedDevicesCategory);
if (scanState == true) {
mActivityStarted = false;
startScanning();
} else {
if (!mAvailableDevicesCategoryIsPresent) {
getPreferenceScreen().addPreference(mAvailableDevicesCategory);
}
}
}
getActivity().invalidateOptionsMenu();
return; // not break
case BluetoothAdapter.STATE_TURNING_OFF:
messageId = R.string.bluetooth_turning_off;
break;
case BluetoothAdapter.STATE_OFF:
messageId = R.string.bluetooth_empty_list_bluetooth_off;
break;
case BluetoothAdapter.STATE_TURNING_ON:
messageId = R.string.bluetooth_turning_on;
break;
}
setDeviceListGroup(preferenceScreen);
removeAllDevices();
mEmptyView.setText(messageId);
getActivity().invalidateOptionsMenu();
}
| private void updateContent(int bluetoothState, boolean scanState) {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
int messageId = 0;
switch (bluetoothState) {
case BluetoothAdapter.STATE_ON:
preferenceScreen.removeAll();
preferenceScreen.setOrderingAsAdded(true);
mDevicePreferenceMap.clear();
// This device
if (mMyDevicePreference == null) {
mMyDevicePreference = new Preference(getActivity());
}
mMyDevicePreference.setTitle(mLocalAdapter.getName());
if (getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {
mMyDevicePreference.setIcon(R.drawable.ic_bt_cellphone); // for phones
} else {
mMyDevicePreference.setIcon(R.drawable.ic_bt_laptop); // for tablets, etc.
}
mMyDevicePreference.setPersistent(false);
mMyDevicePreference.setEnabled(true);
preferenceScreen.addPreference(mMyDevicePreference);
if (mDiscoverableEnabler == null) {
mDiscoverableEnabler = new BluetoothDiscoverableEnabler(getActivity(),
mLocalAdapter, mMyDevicePreference);
mDiscoverableEnabler.resume();
LocalBluetoothManager.getInstance(getActivity()).setDiscoverableEnabler(
mDiscoverableEnabler);
}
// Paired devices category
if (mPairedDevicesCategory == null) {
mPairedDevicesCategory = new PreferenceCategory(getActivity());
} else {
mPairedDevicesCategory.removeAll();
}
addDeviceCategory(mPairedDevicesCategory,
R.string.bluetooth_preference_paired_devices,
BluetoothDeviceFilter.BONDED_DEVICE_FILTER);
int numberOfPairedDevices = mPairedDevicesCategory.getPreferenceCount();
mDiscoverableEnabler.setNumberOfPairedDevices(numberOfPairedDevices);
// Available devices category
if (mAvailableDevicesCategory == null) {
mAvailableDevicesCategory = new ProgressCategory(getActivity(), null);
} else {
mAvailableDevicesCategory.removeAll();
}
addDeviceCategory(mAvailableDevicesCategory,
R.string.bluetooth_preference_found_devices,
BluetoothDeviceFilter.UNBONDED_DEVICE_FILTER);
int numberOfAvailableDevices = mAvailableDevicesCategory.getPreferenceCount();
mAvailableDevicesCategoryIsPresent = true;
if (numberOfAvailableDevices == 0) {
preferenceScreen.removePreference(mAvailableDevicesCategory);
mAvailableDevicesCategoryIsPresent = false;
}
if (numberOfPairedDevices == 0) {
preferenceScreen.removePreference(mPairedDevicesCategory);
if (scanState == true) {
mActivityStarted = false;
startScanning();
} else {
if (!mAvailableDevicesCategoryIsPresent) {
getPreferenceScreen().addPreference(mAvailableDevicesCategory);
}
}
}
getActivity().invalidateOptionsMenu();
return; // not break
case BluetoothAdapter.STATE_TURNING_OFF:
messageId = R.string.bluetooth_turning_off;
break;
case BluetoothAdapter.STATE_OFF:
messageId = R.string.bluetooth_empty_list_bluetooth_off;
break;
case BluetoothAdapter.STATE_TURNING_ON:
messageId = R.string.bluetooth_turning_on;
break;
}
setDeviceListGroup(preferenceScreen);
removeAllDevices();
mEmptyView.setText(messageId);
getActivity().invalidateOptionsMenu();
}
|
diff --git a/modules/library/render/src/main/java/org/geotools/map/MapContent.java b/modules/library/render/src/main/java/org/geotools/map/MapContent.java
index e2d387ab4..7fcc3df22 100644
--- a/modules/library/render/src/main/java/org/geotools/map/MapContent.java
+++ b/modules/library/render/src/main/java/org/geotools/map/MapContent.java
@@ -1,802 +1,805 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2003-2008, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.map;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.event.MapBoundsEvent;
import org.geotools.map.event.MapBoundsListener;
import org.geotools.map.event.MapLayerEvent;
import org.geotools.map.event.MapLayerListEvent;
import org.geotools.map.event.MapLayerListListener;
import org.geotools.map.event.MapLayerListener;
import org.geotools.referencing.CRS;
import org.geotools.util.logging.Logging;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
/**
* Store the contents of a map for display primarily as a list of Layers.
* <p>
* This object is similar to early drafts of the OGC Open Web Service Context specification.
*
* @author Jody Garnett
*
* @source $URL: http://svn.osgeo.org/geotools/trunk/modules/library/render/src/main/java/org/geotools/map/MapContent.java $
* http://svn.osgeo.org/geotools/trunk/modules/library/render/src/main/java/org/geotools
* /map/MapContext.java $
* @version $Id: Map.java 35310 2010-04-30 10:32:15Z jive $
*/
public class MapContent {
/** The logger for the map module. */
static protected final Logger LOGGER = Logging.getLogger("org.geotools.map");
/** List of Layers to be rendered */
private CopyOnWriteArrayList<Layer> layerList;
/** MapLayerListListeners to be notified in the event of change */
private CopyOnWriteArrayList<MapLayerListListener> mapListeners;
/** Map used to hold application specific information */
private HashMap<String, Object> userData;
/** Map title */
private String title;
/** PropertyListener list used for notifications */
private CopyOnWriteArrayList<PropertyChangeListener> propertyListeners;
/**
* Viewport for map rendering.
*
* While the map maintains one viewport internally to better reflect a map context document you
* are free to maintain a seperate viewport; or indeed construct many viewports representing
* tiles to be renderered.
*/
protected MapViewport viewport;
/** Listener used to watch individual layers and report changes to MapLayerListListeners */
private MapLayerListener layerListener;
public MapContent() {
}
/**
* Checks that dispose has been called; producing a warning if needed.
*/
@Override
protected void finalize() throws Throwable {
if( this.layerList != null){
if( !this.layerList.isEmpty()){
LOGGER.severe("Call MapContent dispose() to prevent memory leaks");
}
}
super.finalize();
}
/**
* Clean up any listeners or cached state associated with this MapContent.
* <p>
* Please note that open connections (FeatureSources and GridCoverage readers) are
* the responsibility of your application and are not cleaned up by this method.
*/
public void dispose(){
if( this.mapListeners != null ){
this.mapListeners.clear();
this.mapListeners = null;
}
if( this.layerList != null ){
// remove mapListeners prior to removing layers
for( Layer layer : layerList ){
if( layer == null ) continue;
if( this.layerListener != null ){
layer.removeMapLayerListener(layerListener);
}
layer.dispose();
}
layerList.clear();
layerList = null;
}
if( this.layerListener != null ){
this.layerListener = null;
}
if( this.propertyListeners != null ){
this.propertyListeners.clear();
this.propertyListeners = null;
}
this.title = null;
if( this.userData != null ){
// remove property listeners prior to removing userData
this.userData.clear();
this.userData = null;
}
}
public MapContent(MapContext context){
for( MapLayer mapLayer : context.getLayers() ){
layers().add( mapLayer.toLayer() );
}
if( context.getTitle() != null ){
setTitle( context.getTitle() );
}
if( context.getAbstract() != null ){
getUserData().put("abstract", context.getAbstract() );
}
if( context.getContactInformation() != null ){
getUserData().put("contact", context.getContactInformation() );
}
if( context.getKeywords() != null ){
getUserData().put("keywords", context.getKeywords() );
}
if( context.getAreaOfInterest() != null ){
getViewport().setBounds( context.getAreaOfInterest() );
}
}
@Deprecated
public MapContent(CoordinateReferenceSystem crs) {
getViewport().setCoordinateReferenceSystem(crs);
}
@Deprecated
public MapContent(MapLayer[] array) {
this(array, null);
}
@Deprecated
public MapContent(MapLayer[] array, CoordinateReferenceSystem crs) {
this(array, "Untitled", "", "", null, crs);
}
@Deprecated
public MapContent(MapLayer[] array, String title, String contextAbstract, String contactInformation,
String[] keywords) {
this(array, title, contextAbstract, contactInformation, keywords, null);
}
@Deprecated
public MapContent(MapLayer[] array, String title, String contextAbstract, String contactInformation,
String[] keywords, final CoordinateReferenceSystem crs) {
if( array != null ){
for (MapLayer mapLayer : array) {
if( mapLayer == null ){
continue;
}
Layer layer = mapLayer.toLayer();
layers().add( layer );
}
}
if (title != null) {
setTitle(title);
}
if (contextAbstract != null) {
getUserData().put("abstract", contextAbstract);
}
if (contactInformation != null) {
getUserData().put("contact", contactInformation);
}
if (keywords != null) {
getUserData().put("keywords", keywords);
}
if (crs != null) {
getViewport().setCoordinateReferenceSystem(crs);
}
}
/**
* Register interest in receiving a {@link LayerListEvent}. A <code>LayerListEvent</code> is
* sent if a layer is added or removed, but not if the data within a layer changes.
*
* @param listener
* The object to notify when Layers have changed.
*/
public void addMapLayerListListener(MapLayerListListener listener) {
if (mapListeners == null) {
mapListeners = new CopyOnWriteArrayList<MapLayerListListener>();
}
boolean added = mapListeners.addIfAbsent(listener);
if (added && mapListeners.size() == 1) {
listenToMapLayers(true);
}
}
/**
* Listen to the map layers; passing any events on to our own mapListListeners.
* <p>
* This method only has an effect if we have any actuall mapListListeners.
*
* @param listen
* True to connect to all the layers and listen to events
*/
protected synchronized void listenToMapLayers(boolean listen) {
if( mapListeners == null || mapListeners.isEmpty()){
return; // not worth listening nobody is interested
}
if (layerListener == null) {
layerListener = new MapLayerListener() {
public void layerShown(MapLayerEvent event) {
Layer layer = (Layer) event.getSource();
int index = layers().indexOf(layer);
fireLayerEvent(layer, index, event);
}
public void layerSelected(MapLayerEvent event) {
Layer layer = (Layer) event.getSource();
int index = layers().indexOf(layer);
fireLayerEvent(layer, index, event);
}
public void layerHidden(MapLayerEvent event) {
Layer layer = (Layer) event.getSource();
int index = layers().indexOf(layer);
fireLayerEvent(layer, index, event);
}
public void layerDeselected(MapLayerEvent event) {
Layer layer = (Layer) event.getSource();
int index = layers().indexOf(layer);
fireLayerEvent(layer, index, event);
}
public void layerChanged(MapLayerEvent event) {
Layer layer = (Layer) event.getSource();
int index = layers().indexOf(layer);
fireLayerEvent(layer, index, event);
}
};
}
if (listen) {
for (Layer layer : layers()) {
layer.addMapLayerListener(layerListener);
}
} else {
for (Layer layer : layers()) {
layer.removeMapLayerListener(layerListener);
}
}
}
/**
* Remove interest in receiving {@link LayerListEvent}.
*
* @param listener
* The object to stop sending <code>LayerListEvent</code>s.
*/
public void removeMapLayerListListener(MapLayerListListener listener) {
if (mapListeners != null) {
mapListeners.remove(listener);
}
}
/**
* Add a new layer (if not already present).
* <p>
* In an interactive setting this will trigger a {@link LayerListEvent}
*
* @param layer
* @return true if the layer was added
*/
public boolean addLayer(Layer layer) {
return layers().addIfAbsent(layer);
}
/**
* Remove a layer, if present, and trigger a {@link LayerListEvent}.
*
* @param layer
* a MapLayer that will be added.
*
* @return true if the layer has been removed
*/
public boolean removeLayer(Layer layer) {
return layers().remove(layer);
}
/**
* Moves a layer from a position to another. Will fire a MapLayerListEvent
*
* @param sourcePosition
* the layer current position
* @param destPosition
* the layer new position
*/
public void moveLayer(int sourcePosition, int destPosition) {
List<Layer> layers = layers();
Layer destLayer = layers.get(destPosition);
Layer sourceLayer = layers.get(sourcePosition);
layers.set(destPosition, sourceLayer);
layers.set(sourcePosition, destLayer);
}
/**
* Direct access to the layer list; contents arranged by zorder.
* <p>
* Please note this list is live and modifications made to the list will trigger
* {@link LayerListEvent}
*
* @return Direct access to layers
*/
public synchronized CopyOnWriteArrayList<Layer> layers() {
if (layerList == null) {
layerList = new CopyOnWriteArrayList<Layer>() {
private static final long serialVersionUID = 8011733882551971475L;
public void add(int index, Layer element) {
super.add(index, element);
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, index, index);
}
@Override
public boolean add(Layer element) {
boolean added = super.add(element);
if (added) {
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, size() - 1, size() - 1);
}
return added;
}
public boolean addAll(Collection<? extends Layer> c) {
int start = size() - 1;
boolean added = super.addAll(c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
public boolean addAll(int index, Collection<? extends Layer> c) {
boolean added = super.addAll(index, c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, index, size() - 1);
return added;
}
@Override
public int addAllAbsent(Collection<? extends Layer> c) {
int start = size() - 1;
int added = super.addAllAbsent(c);
if( layerListener != null ){
// taking the risk that layer is correctly impelmented and will
// not have layerListener not mapped
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
@Override
- public boolean addIfAbsent(Layer e) {
- boolean added = super.addIfAbsent(e);
+ public boolean addIfAbsent(Layer element) {
+ boolean added = super.addIfAbsent(element);
if (added) {
- fireLayerAdded(e, size() - 1, size() - 1);
+ if (layerListener != null) {
+ element.addMapLayerListener(layerListener);
+ }
+ fireLayerAdded(element, size() - 1, size() - 1);
}
return added;
}
@Override
public void clear() {
for( Layer element : this ){
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
super.clear();
fireLayerRemoved(null, -1, -1);
}
@Override
public Layer remove(int index) {
Layer removed = super.remove(index);
fireLayerRemoved(removed, index, index);
if( layerListener != null ){
removed.removeMapLayerListener( layerListener );
}
removed.dispose();
return removed;
}
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed) {
fireLayerRemoved((Layer) o, -1, -1);
if( o instanceof Layer ){
Layer element = (Layer) o;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
return removed;
}
@Override
public boolean removeAll(Collection<?> c) {
for( Object obj : c ){
if( !contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.removeAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
@Override
public boolean retainAll(Collection<?> c) {
for( Object obj : c ){
if( contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.retainAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
};
}
return layerList;
}
protected void fireLayerAdded(Layer element, int fromIndex, int toIndex) {
if (mapListeners == null) {
return;
}
MapLayerListEvent event = new MapLayerListEvent(this, element, fromIndex, toIndex);
for (MapLayerListListener mapLayerListListener : mapListeners) {
try {
mapLayerListListener.layerAdded(event);
} catch (Throwable t) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(),
"layerAdded", t.getLocalizedMessage(), t);
}
}
}
}
protected void fireLayerRemoved(Layer element, int fromIndex, int toIndex) {
if (mapListeners == null) {
return;
}
MapLayerListEvent event = new MapLayerListEvent(this, element, fromIndex, toIndex);
for (MapLayerListListener mapLayerListListener : mapListeners) {
try {
mapLayerListListener.layerRemoved(event);
} catch (Throwable t) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(),
"layerAdded", t.getLocalizedMessage(), t);
}
}
}
}
protected void fireLayerEvent(Layer element, int index, MapLayerEvent layerEvent) {
if (mapListeners == null) {
return;
}
MapLayerListEvent mapEvent = new MapLayerListEvent(this, element, index, layerEvent);
for (MapLayerListListener mapLayerListListener : mapListeners) {
try {
mapLayerListListener.layerChanged(mapEvent);
} catch (Throwable t) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(),
"layerAdded", t.getLocalizedMessage(), t);
}
}
}
}
/**
* Get the bounding box of all the layers in this Map. If all the layers cannot determine the
* bounding box in the speed required for each layer, then null is returned. The bounds will be
* expressed in the Map coordinate system.
*
* @return The bounding box of the features or null if unknown and too expensive for the method
* to calculate.
*
* @throws IOException
* if an IOException occurs while accessing the FeatureSource bounds
*/
public ReferencedEnvelope getMaxBounds() {
CoordinateReferenceSystem mapCrs = null;
if (viewport != null) {
mapCrs = viewport.getCoordianteReferenceSystem();
}
ReferencedEnvelope maxBounds = null;
for (Layer layer : layers()) {
if (layer == null) {
continue;
}
try {
ReferencedEnvelope layerBounds = layer.getBounds();
if (layerBounds == null || layerBounds.isEmpty() || layerBounds.isNull()) {
continue;
}
if (mapCrs == null) {
// crs for the map is not defined; let us start with the first CRS we see then!
maxBounds = new ReferencedEnvelope(layerBounds);
mapCrs = layerBounds.getCoordinateReferenceSystem();
continue;
}
ReferencedEnvelope normalized;
if (CRS.equalsIgnoreMetadata(mapCrs, layerBounds.getCoordinateReferenceSystem())) {
normalized = layerBounds;
} else {
try {
normalized = layerBounds.transform(mapCrs, true);
} catch (Exception e) {
LOGGER.log(Level.FINE, "Unable to transform: {0}", e);
continue;
}
}
if (maxBounds == null) {
maxBounds = normalized;
} else {
maxBounds.expandToInclude(normalized);
}
} catch (Throwable eek) {
LOGGER.warning("Unable to determine bounds of " + layer + ":" + eek);
}
}
if (maxBounds == null && mapCrs != null) {
maxBounds = new ReferencedEnvelope(mapCrs);
}
return maxBounds;
}
//
// Viewport Information
//
/**
* Viewport describing the area visible on screen.
* <p>
* Applications may create multiple viewports (perhaps to render tiles of content); the viewport
* recorded here is intended for interactive applications where it is helpful to have a single
* viewport representing what the user is seeing on screen.
* <p>
* With that in mind; if the user has not already supplied a viewport one will be created:
* <ul>
* <li>The viewport will be configured to show the extent of the current layers as provided by
* {@link #getMaxBounds()}.</li>
* <li>The viewport will have an empty {@link MapViewport#getBounds()} if no layers have been
* added yet.</li>
* </ul>
* @return MapViewport describing how to draw this map
*/
public synchronized MapViewport getViewport() {
if (viewport == null) {
viewport = new MapViewport( getMaxBounds() );
}
return viewport;
}
/**
* Register interest in receiving {@link MapBoundsEvent}s.
*
* @param listener
* The object to notify when the area of interest has changed.
*/
public void addMapBoundsListener(MapBoundsListener listener) {
getViewport().addMapBoundsListener(listener);
}
/**
* Remove interest in receiving a {@link BoundingBoxEvent}s.
*
* @param listener
* The object to stop sending change events.
*/
public void removeMapBoundsListener(MapBoundsListener listener) {
getViewport().removeMapBoundsListener(listener);
}
/**
* The extent of the map currently (sometimes called the map "viewport".
* <p>
* Note Well: The bounds should match your screen aspect ratio (or the map will appear
* squashed). Please note this only covers spatial extent; you may wish to use the user data map
* to record the current viewport time or elevation.
*/
ReferencedEnvelope getBounds() {
return getViewport().getBounds();
}
/**
* The coordinate reference system used for rendering the map.
* <p>
* The coordinate reference system used for rendering is often considered to be the "world"
* coordinate reference system; this is distinct from the coordinate reference system used for
* each layer (which is often data dependent).
* </p>
*
* @return coordinate reference system used for rendering the map.
*/
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
return getViewport().getCoordianteReferenceSystem();
}
/**
* Set the <code>CoordinateReferenceSystem</code> for this map's internal viewport.
*
* @param crs
* @throws FactoryException
* @throws TransformException
*/
void setCoordinateReferenceSystem(CoordinateReferenceSystem crs) {
getViewport().setCoordinateReferenceSystem(crs);
}
//
// Properties
//
/**
* Registers PropertyChangeListener to receive events.
*
* @param listener
* The listener to register.
*/
public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) {
if (propertyListeners == null) {
propertyListeners = new CopyOnWriteArrayList<java.beans.PropertyChangeListener>();
}
if (!propertyListeners.contains(listener)) {
propertyListeners.add(listener);
}
}
/**
* Removes PropertyChangeListener from the list of listeners.
*
* @param listener
* The listener to remove.
*/
public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) {
if (propertyListeners != null) {
propertyListeners.remove(listener);
}
}
/**
* As an example it can be used to record contact details, map abstract, keywords and so forth
* for an OGC "Open Web Service Context" document.
* <p>
* Modifications to the userData will result in a propertyChange event.
* </p>
*
* @return
*/
public synchronized java.util.Map<String, Object> getUserData() {
if (userData == null) {
userData = new HashMap<String, Object>() {
private static final long serialVersionUID = 8011733882551971475L;
public Object put(String key, Object value) {
Object old = super.put(key, value);
fireProperty(key, old, value);
return old;
}
public Object remove(Object key) {
Object old = super.remove(key);
fireProperty((String) key, old, null);
return old;
}
@Override
public void putAll(java.util.Map<? extends String, ? extends Object> m) {
super.putAll(m);
fireProperty("userData", null, null);
}
@Override
public void clear() {
super.clear();
fireProperty("userData", null, null);
}
};
}
return this.userData;
}
/**
* Get the title, returns an empty string if it has not been set yet.
*
* @return the title, or an empty string if it has not been set.
*/
public String getTitle() {
return title;
}
/**
* Set the title of this context.
*
* @param title
* the title.
*/
public void setTitle(String title) {
String old = this.title;
this.title = title;
fireProperty("title", old, title);
}
protected void fireProperty(String propertyName, Object old, Object value) {
if (propertyListeners == null) {
return;
}
PropertyChangeEvent event = new PropertyChangeEvent(this, "propertyName", old, value);
for (PropertyChangeListener propertyChangeListener : propertyListeners) {
try {
propertyChangeListener.propertyChange(event);
} catch (Throwable t) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.logp(Level.FINE, propertyChangeListener.getClass().getName(),
"propertyChange", t.getLocalizedMessage(), t);
}
}
}
}
}
| false | true | public synchronized CopyOnWriteArrayList<Layer> layers() {
if (layerList == null) {
layerList = new CopyOnWriteArrayList<Layer>() {
private static final long serialVersionUID = 8011733882551971475L;
public void add(int index, Layer element) {
super.add(index, element);
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, index, index);
}
@Override
public boolean add(Layer element) {
boolean added = super.add(element);
if (added) {
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, size() - 1, size() - 1);
}
return added;
}
public boolean addAll(Collection<? extends Layer> c) {
int start = size() - 1;
boolean added = super.addAll(c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
public boolean addAll(int index, Collection<? extends Layer> c) {
boolean added = super.addAll(index, c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, index, size() - 1);
return added;
}
@Override
public int addAllAbsent(Collection<? extends Layer> c) {
int start = size() - 1;
int added = super.addAllAbsent(c);
if( layerListener != null ){
// taking the risk that layer is correctly impelmented and will
// not have layerListener not mapped
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
@Override
public boolean addIfAbsent(Layer e) {
boolean added = super.addIfAbsent(e);
if (added) {
fireLayerAdded(e, size() - 1, size() - 1);
}
return added;
}
@Override
public void clear() {
for( Layer element : this ){
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
super.clear();
fireLayerRemoved(null, -1, -1);
}
@Override
public Layer remove(int index) {
Layer removed = super.remove(index);
fireLayerRemoved(removed, index, index);
if( layerListener != null ){
removed.removeMapLayerListener( layerListener );
}
removed.dispose();
return removed;
}
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed) {
fireLayerRemoved((Layer) o, -1, -1);
if( o instanceof Layer ){
Layer element = (Layer) o;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
return removed;
}
@Override
public boolean removeAll(Collection<?> c) {
for( Object obj : c ){
if( !contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.removeAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
@Override
public boolean retainAll(Collection<?> c) {
for( Object obj : c ){
if( contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.retainAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
};
}
return layerList;
}
| public synchronized CopyOnWriteArrayList<Layer> layers() {
if (layerList == null) {
layerList = new CopyOnWriteArrayList<Layer>() {
private static final long serialVersionUID = 8011733882551971475L;
public void add(int index, Layer element) {
super.add(index, element);
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, index, index);
}
@Override
public boolean add(Layer element) {
boolean added = super.add(element);
if (added) {
if( layerListener != null ){
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, size() - 1, size() - 1);
}
return added;
}
public boolean addAll(Collection<? extends Layer> c) {
int start = size() - 1;
boolean added = super.addAll(c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
public boolean addAll(int index, Collection<? extends Layer> c) {
boolean added = super.addAll(index, c);
if( layerListener != null ){
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, index, size() - 1);
return added;
}
@Override
public int addAllAbsent(Collection<? extends Layer> c) {
int start = size() - 1;
int added = super.addAllAbsent(c);
if( layerListener != null ){
// taking the risk that layer is correctly impelmented and will
// not have layerListener not mapped
for( Layer element : c ){
element.addMapLayerListener(layerListener);
}
}
fireLayerAdded(null, start, size() - 1);
return added;
}
@Override
public boolean addIfAbsent(Layer element) {
boolean added = super.addIfAbsent(element);
if (added) {
if (layerListener != null) {
element.addMapLayerListener(layerListener);
}
fireLayerAdded(element, size() - 1, size() - 1);
}
return added;
}
@Override
public void clear() {
for( Layer element : this ){
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
super.clear();
fireLayerRemoved(null, -1, -1);
}
@Override
public Layer remove(int index) {
Layer removed = super.remove(index);
fireLayerRemoved(removed, index, index);
if( layerListener != null ){
removed.removeMapLayerListener( layerListener );
}
removed.dispose();
return removed;
}
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed) {
fireLayerRemoved((Layer) o, -1, -1);
if( o instanceof Layer ){
Layer element = (Layer) o;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
return removed;
}
@Override
public boolean removeAll(Collection<?> c) {
for( Object obj : c ){
if( !contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.removeAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
@Override
public boolean retainAll(Collection<?> c) {
for( Object obj : c ){
if( contains(obj) ){
continue;
}
if( obj instanceof Layer ){
Layer element = (Layer) obj;
if( layerListener != null ){
element.removeMapLayerListener( layerListener );
}
element.dispose();
}
}
boolean removed = super.retainAll(c);
fireLayerRemoved(null, 0, size() - 1);
return removed;
}
};
}
return layerList;
}
|
diff --git a/modules/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxConverter.java b/modules/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxConverter.java
index 183429d2c..0e38476c8 100644
--- a/modules/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxConverter.java
+++ b/modules/org.restlet.ext.jibx/src/org/restlet/ext/jibx/JibxConverter.java
@@ -1,217 +1,217 @@
/**
* Copyright 2005-2011 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.ext.jibx;
import java.io.IOException;
import java.util.List;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.JiBXException;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.engine.converter.ConverterHelper;
import org.restlet.engine.resource.VariantInfo;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.Resource;
/**
* A JiBX converter helper to convert from JiBX objects to JibxRepresentation
* and vice versa. It only supports objects that are not bound several times
* using several binding names.
*
* @author Thierry Boileau
*/
public class JibxConverter extends ConverterHelper {
private static final VariantInfo VARIANT_APPLICATION_ALL_XML = new VariantInfo(
MediaType.APPLICATION_ALL_XML);
private static final VariantInfo VARIANT_APPLICATION_XML = new VariantInfo(
MediaType.APPLICATION_XML);
private static final VariantInfo VARIANT_TEXT_XML = new VariantInfo(
MediaType.TEXT_XML);
@Override
public List<Class<?>> getObjectClasses(Variant source) {
List<Class<?>> result = null;
if (VARIANT_APPLICATION_ALL_XML.isCompatible(source)
|| VARIANT_APPLICATION_XML.isCompatible(source)
|| VARIANT_TEXT_XML.isCompatible(source)) {
result = addObjectClass(result, JibxRepresentation.class);
}
return result;
}
@Override
public List<VariantInfo> getVariants(Class<?> source) {
List<VariantInfo> result = null;
if (isJibxBoundClass(source)
|| JibxRepresentation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_APPLICATION_ALL_XML);
result = addVariant(result, VARIANT_APPLICATION_XML);
result = addVariant(result, VARIANT_TEXT_XML);
}
return result;
}
/**
* Indicates if the class is bound by a Jibx factory.
*
* @param source
* The class to test.
* @return True if the class is bound by a Jibx factory.
*/
private boolean isJibxBoundClass(Class<?> source) {
boolean result = false;
try {
if ((source != null)
&& (BindingDirectory.getFactory(source) != null)) {
result = true;
}
} catch (JiBXException e) {
// This may be caused by the fact that the source class is bound
// several times which requires the knowledge of the binding name.
}
return result;
}
@Override
public float score(Object source, Variant target, Resource resource) {
float result = -1.0F;
if (source != null
&& (source instanceof JibxRepresentation<?> || isJibxBoundClass(source
.getClass()))) {
if (target == null) {
result = 0.5F;
} else if (MediaType.APPLICATION_ALL_XML.isCompatible(target
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_XML.isCompatible(target
.getMediaType())) {
result = 1.0F;
} else if (MediaType.TEXT_XML.isCompatible(target.getMediaType())) {
result = 1.0F;
} else {
// Allow for JiBX object to be used for JSON and other
// representations
result = 0.5F;
}
}
return result;
}
@Override
public <T> float score(Representation source, Class<T> target,
Resource resource) {
float result = -1.0F;
if (source != null) {
if (source instanceof JibxRepresentation<?>) {
result = 1.0F;
} else if (JibxRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (isJibxBoundClass(target)
|| JibxRepresentation.class.isAssignableFrom(source
.getClass())) {
result = 1.0F;
}
}
return result;
}
@Override
public <T> T toObject(Representation source, Class<T> target,
Resource resource) throws IOException {
Object result = null;
if (JibxRepresentation.class.isAssignableFrom(target)) {
result = new JibxRepresentation<T>(source, target);
} else if (isJibxBoundClass(target)) {
try {
result = new JibxRepresentation<T>(source, target).getObject();
} catch (JiBXException e) {
throw new IOException(
- "Cannot convert the given representation to an object of this class using Jibx converter "
+ "Cannot convert the given representation to an object of this class using Jibx converter "
+ target + " due to " + e.getMessage());
}
} else if (target == null) {
if (source instanceof JibxRepresentation<?>) {
try {
result = ((JibxRepresentation<?>) source).getObject();
} catch (JiBXException e) {
throw new IOException(
"Cannot retrieve the wrapped object inside the JiBX representation due to "
+ e.getMessage());
}
}
}
return target.cast(result);
}
@Override
public Representation toRepresentation(Object source, Variant target,
Resource resource) {
Representation result = null;
if (isJibxBoundClass(source.getClass())) {
result = new JibxRepresentation<Object>(target.getMediaType(),
source);
} else if (source instanceof JibxRepresentation<?>) {
result = (Representation) source;
}
return result;
}
@Override
public <T> void updatePreferences(List<Preference<MediaType>> preferences,
Class<T> entity) {
if (isJibxBoundClass(entity)
|| JibxRepresentation.class.isAssignableFrom(entity)) {
updatePreferences(preferences, MediaType.APPLICATION_ALL_XML, 1.0F);
updatePreferences(preferences, MediaType.APPLICATION_XML, 1.0F);
updatePreferences(preferences, MediaType.TEXT_XML, 1.0F);
}
}
}
| true | true | public <T> T toObject(Representation source, Class<T> target,
Resource resource) throws IOException {
Object result = null;
if (JibxRepresentation.class.isAssignableFrom(target)) {
result = new JibxRepresentation<T>(source, target);
} else if (isJibxBoundClass(target)) {
try {
result = new JibxRepresentation<T>(source, target).getObject();
} catch (JiBXException e) {
throw new IOException(
"Cannot convert the given representation to an object of this class using Jibx converter "
+ target + " due to " + e.getMessage());
}
} else if (target == null) {
if (source instanceof JibxRepresentation<?>) {
try {
result = ((JibxRepresentation<?>) source).getObject();
} catch (JiBXException e) {
throw new IOException(
"Cannot retrieve the wrapped object inside the JiBX representation due to "
+ e.getMessage());
}
}
}
return target.cast(result);
}
| public <T> T toObject(Representation source, Class<T> target,
Resource resource) throws IOException {
Object result = null;
if (JibxRepresentation.class.isAssignableFrom(target)) {
result = new JibxRepresentation<T>(source, target);
} else if (isJibxBoundClass(target)) {
try {
result = new JibxRepresentation<T>(source, target).getObject();
} catch (JiBXException e) {
throw new IOException(
"Cannot convert the given representation to an object of this class using Jibx converter "
+ target + " due to " + e.getMessage());
}
} else if (target == null) {
if (source instanceof JibxRepresentation<?>) {
try {
result = ((JibxRepresentation<?>) source).getObject();
} catch (JiBXException e) {
throw new IOException(
"Cannot retrieve the wrapped object inside the JiBX representation due to "
+ e.getMessage());
}
}
}
return target.cast(result);
}
|
diff --git a/yabe/app/Bootstrap.java b/yabe/app/Bootstrap.java
index b0dfae5..6aa7cef 100644
--- a/yabe/app/Bootstrap.java
+++ b/yabe/app/Bootstrap.java
@@ -1,15 +1,15 @@
import models.User;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import play.test.Fixtures;
@OnApplicationStart
public class Bootstrap extends Job {
@Override
public void doJob() throws Exception {
if (User.count() == 0) {
- Fixtures.loadYaml("data.yml");
+ Fixtures.loadYaml("initial-data.yml");
}
}
}
| true | true | public void doJob() throws Exception {
if (User.count() == 0) {
Fixtures.loadYaml("data.yml");
}
}
| public void doJob() throws Exception {
if (User.count() == 0) {
Fixtures.loadYaml("initial-data.yml");
}
}
|
diff --git a/src/ibis/impl/messagePassing/ReceivePortNameServerClient.java b/src/ibis/impl/messagePassing/ReceivePortNameServerClient.java
index 2527a6e3..01effa51 100644
--- a/src/ibis/impl/messagePassing/ReceivePortNameServerClient.java
+++ b/src/ibis/impl/messagePassing/ReceivePortNameServerClient.java
@@ -1,298 +1,298 @@
/* $Id$ */
package ibis.impl.messagePassing;
import ibis.io.Conversion;
import ibis.util.ConditionVariable;
import java.io.IOException;
/**
* messagePassing implementation of NameServer: the ReceivePort naming client
*/
final class ReceivePortNameServerClient implements
ReceivePortNameServerProtocol {
static {
if (ReceivePortNameServerProtocol.DEBUG) {
if (Ibis.myIbis.myCpu == 0) {
System.err.println("Turn on ReceivePortNS.DEBUG");
}
}
}
private class Bind extends Syncer {
public boolean satisfied() {
return bound;
}
public void signal() {
bound = true;
wakeup();
}
private boolean ns_busy = false;
private ConditionVariable ns_free = Ibis.myIbis.createCV();
private boolean bound;
void bind(String name, ReceivePortIdentifier id) throws IOException {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Try to bind ReceivePortId " + id + " ibis "
+ id.ibis().name());
}
// request a new Port.
Ibis.myIbis.checkLockNotOwned();
Ibis.myIbis.lock();
try {
while (ns_busy) {
try {
ns_free.cv_wait();
} catch (InterruptedException e) {
// ignore
}
}
ns_busy = true;
bound = false;
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Call this rp-ns bind() \"" + name + "\"");
// Thread.dumpStack();
}
ns_bind(name, id.getSerialForm());
if (ReceivePortNameServerProtocol.DEBUG) {
if (bound) {
System.err.println("******** Reply arrives early, bind="
+ this);
}
}
Ibis.myIbis.waitPolling(this, 0, Poll.PREEMPTIVE);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Bind reply arrived, client woken up" + this);
}
ns_busy = false;
ns_free.cv_signal();
} finally {
Ibis.myIbis.unlock();
}
}
}
/* Called from native */
private void bind_reply() {
Ibis.myIbis.checkLockOwned();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Bind reply arrives, signal client" + this + " bind = "
+ bind);
}
bind.signal();
}
native void ns_bind(String name, byte[] recvPortId);
private Bind bind = new Bind();
public void bind(String name, ReceivePortIdentifier id) throws IOException {
bind.bind(name, id);
}
private class Lookup extends Syncer {
public boolean satisfied() {
return ri != null;
}
private boolean ns_busy = false;
private ConditionVariable ns_free = Ibis.myIbis.createCV();
ReceivePortIdentifier ri;
int seqno = 0;
int expected_seqno = 0;
private static final int BACKOFF_MILLIS = 100;
public ibis.ipl.ReceivePortIdentifier lookup(String name, long timeout)
throws IOException {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Lookup receive port \"" + name + "\"");
}
Ibis.myIbis.lock();
while (ns_busy) {
try {
ns_free.cv_wait();
} catch (InterruptedException e) {
// ignore
}
}
ns_busy = true;
expected_seqno = seqno++;
Ibis.myIbis.unlock();
long start = System.currentTimeMillis();
long last_try = start - BACKOFF_MILLIS;
while (true) {
long now = System.currentTimeMillis();
if (timeout > 0 && now - start > timeout) {
Ibis.myIbis.lock();
ns_busy = false;
ns_free.cv_signal();
Ibis.myIbis.unlock();
throw new ibis.ipl.ConnectionTimedOutException(
"messagePassing.Ibis ReceivePort lookup failed");
}
if (now - last_try >= BACKOFF_MILLIS) {
Ibis.myIbis.lock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Got lock ...");
}
try {
ri = null;
ns_lookup(name, expected_seqno);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Wait for my lookup \"" + name
+ "\" reply " + this);
}
Ibis.myIbis.waitPolling(this, BACKOFF_MILLIS,
Poll.PREEMPTIVE);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Lookup reply says ri = " + ri
+ " this = " + this);
}
if (ri != null) {
- if (ri.cpu != -1 && name.equals(ri.name())) {
+ if (ri.cpu != -1) {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " clear lookup.ns_busy" + this);
}
ns_busy = false;
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " signal potential waiters");
}
ns_free.cv_signal();
// System.err.println("ReceivePortNameServerClient: got " + ri);
return ri;
}
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("ReceivePortNameServerClient: requested " + name + ", but got " + ri + ", dropped ...");
}
ri = null;
}
} finally {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Releasing lock ...");
}
Ibis.myIbis.unlock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Released lock ...");
}
}
last_try = System.currentTimeMillis();
}
/* Thread.yield(); */
if (false) {
// I don't see why I should sleep here, when waitPolling
// also takes a timeout argument
try {
Thread.sleep(BACKOFF_MILLIS);
} catch (InterruptedException e) {
// Well, if somebody interrupts us, would there be news?
}
}
}
}
}
native void ns_lookup(String name, int seqno);
/* Called from native */
private void lookup_reply(byte[] rcvePortId, int seqno) {
Ibis.myIbis.checkLockOwned();
if (lookup.expected_seqno != seqno) {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: lookup reply: got seqno "
+ seqno + ", expected " + lookup.expected_seqno);
}
return;
}
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: lookup reply " + rcvePortId + " "
+ lookup);
}
if (rcvePortId != null) {
try {
lookup.ri = (ReceivePortIdentifier) Conversion.byte2object(
rcvePortId);
lookup.signal();
} catch (ClassNotFoundException e) {
System.err.println("Cannot deserialize ReceivePortId");
Thread.dumpStack();
} catch (IOException e) {
System.err.println("Cannot deserialize ReceivePortId");
Thread.dumpStack();
}
}
else {
lookup.ri = ReceivePortIdentifier.dummy;
}
}
private Lookup lookup = new Lookup();
public ibis.ipl.ReceivePortIdentifier lookup(String name, long timeout)
throws IOException {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Ibis.myIbis.myCpu
+ ": Do a ReceivePortId NS lookup(" + name + ", " + timeout
+ ") in " + lookup);
}
return lookup.lookup(name, timeout);
}
public ibis.ipl.ReceivePortIdentifier[] query(ibis.ipl.IbisIdentifier ident)
throws IOException {
/* not implemented yet */
return null;
}
private native void ns_unbind(String public_name);
void unbind(String name) {
Ibis.myIbis.lock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Ibis.myIbis.myCpu + ": Do an UNBIND of \""
+ name + "\"");
}
ns_unbind(name);
Ibis.myIbis.unlock();
}
}
| true | true | public ibis.ipl.ReceivePortIdentifier lookup(String name, long timeout)
throws IOException {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Lookup receive port \"" + name + "\"");
}
Ibis.myIbis.lock();
while (ns_busy) {
try {
ns_free.cv_wait();
} catch (InterruptedException e) {
// ignore
}
}
ns_busy = true;
expected_seqno = seqno++;
Ibis.myIbis.unlock();
long start = System.currentTimeMillis();
long last_try = start - BACKOFF_MILLIS;
while (true) {
long now = System.currentTimeMillis();
if (timeout > 0 && now - start > timeout) {
Ibis.myIbis.lock();
ns_busy = false;
ns_free.cv_signal();
Ibis.myIbis.unlock();
throw new ibis.ipl.ConnectionTimedOutException(
"messagePassing.Ibis ReceivePort lookup failed");
}
if (now - last_try >= BACKOFF_MILLIS) {
Ibis.myIbis.lock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Got lock ...");
}
try {
ri = null;
ns_lookup(name, expected_seqno);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Wait for my lookup \"" + name
+ "\" reply " + this);
}
Ibis.myIbis.waitPolling(this, BACKOFF_MILLIS,
Poll.PREEMPTIVE);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Lookup reply says ri = " + ri
+ " this = " + this);
}
if (ri != null) {
if (ri.cpu != -1 && name.equals(ri.name())) {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " clear lookup.ns_busy" + this);
}
ns_busy = false;
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " signal potential waiters");
}
ns_free.cv_signal();
// System.err.println("ReceivePortNameServerClient: got " + ri);
return ri;
}
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("ReceivePortNameServerClient: requested " + name + ", but got " + ri + ", dropped ...");
}
ri = null;
}
} finally {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Releasing lock ...");
}
Ibis.myIbis.unlock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Released lock ...");
}
}
last_try = System.currentTimeMillis();
}
/* Thread.yield(); */
if (false) {
// I don't see why I should sleep here, when waitPolling
// also takes a timeout argument
try {
Thread.sleep(BACKOFF_MILLIS);
} catch (InterruptedException e) {
// Well, if somebody interrupts us, would there be news?
}
}
}
}
| public ibis.ipl.ReceivePortIdentifier lookup(String name, long timeout)
throws IOException {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "Lookup receive port \"" + name + "\"");
}
Ibis.myIbis.lock();
while (ns_busy) {
try {
ns_free.cv_wait();
} catch (InterruptedException e) {
// ignore
}
}
ns_busy = true;
expected_seqno = seqno++;
Ibis.myIbis.unlock();
long start = System.currentTimeMillis();
long last_try = start - BACKOFF_MILLIS;
while (true) {
long now = System.currentTimeMillis();
if (timeout > 0 && now - start > timeout) {
Ibis.myIbis.lock();
ns_busy = false;
ns_free.cv_signal();
Ibis.myIbis.unlock();
throw new ibis.ipl.ConnectionTimedOutException(
"messagePassing.Ibis ReceivePort lookup failed");
}
if (now - last_try >= BACKOFF_MILLIS) {
Ibis.myIbis.lock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Got lock ...");
}
try {
ri = null;
ns_lookup(name, expected_seqno);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Wait for my lookup \"" + name
+ "\" reply " + this);
}
Ibis.myIbis.waitPolling(this, BACKOFF_MILLIS,
Poll.PREEMPTIVE);
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " Lookup reply says ri = " + ri
+ " this = " + this);
}
if (ri != null) {
if (ri.cpu != -1) {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " clear lookup.ns_busy" + this);
}
ns_busy = false;
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println(Thread.currentThread()
+ "ReceivePortNSClient: "
+ " signal potential waiters");
}
ns_free.cv_signal();
// System.err.println("ReceivePortNameServerClient: got " + ri);
return ri;
}
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("ReceivePortNameServerClient: requested " + name + ", but got " + ri + ", dropped ...");
}
ri = null;
}
} finally {
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Releasing lock ...");
}
Ibis.myIbis.unlock();
if (ReceivePortNameServerProtocol.DEBUG) {
System.err.println("Released lock ...");
}
}
last_try = System.currentTimeMillis();
}
/* Thread.yield(); */
if (false) {
// I don't see why I should sleep here, when waitPolling
// also takes a timeout argument
try {
Thread.sleep(BACKOFF_MILLIS);
} catch (InterruptedException e) {
// Well, if somebody interrupts us, would there be news?
}
}
}
}
|
diff --git a/src/com/tools/tvguide/activities/AlarmAlertActivity.java b/src/com/tools/tvguide/activities/AlarmAlertActivity.java
index f7ca494..098c6ef 100644
--- a/src/com/tools/tvguide/activities/AlarmAlertActivity.java
+++ b/src/com/tools/tvguide/activities/AlarmAlertActivity.java
@@ -1,86 +1,90 @@
package com.tools.tvguide.activities;
import java.util.HashMap;
import com.tools.tvguide.R;
import com.tools.tvguide.managers.AppEngine;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
public class AlarmAlertActivity extends Activity
{
public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
final MediaPlayer localMediaPlayer = MediaPlayer.create(this, getDefaultRingtoneUri(4));
- localMediaPlayer.setLooping(true);
- localMediaPlayer.start();
- final String channelId = getIntent().getStringExtra("channel_id");
- final String channelName = getIntent().getStringExtra("channel_name");
- final String program = getIntent().getStringExtra("program");
- final String day = getIntent().getStringExtra("day");
+ if (localMediaPlayer != null)
+ {
+ localMediaPlayer.setLooping(true);
+ localMediaPlayer.start();
+ }
+ final String channelId = getIntent().getStringExtra("channel_id") == null ? "" : getIntent().getStringExtra("channel_id");
+ final String channelName = getIntent().getStringExtra("channel_name") == null ? "" : getIntent().getStringExtra("channel_name");
+ final String program = getIntent().getStringExtra("program") == null ? "" : getIntent().getStringExtra("program");
+ final String day = getIntent().getStringExtra("day") == null ? "1" : getIntent().getStringExtra("day");
AlertDialog dialog = new AlertDialog.Builder(AlarmAlertActivity.this).setIcon(R.drawable.clock)
.setTitle(channelName)
.setMessage(program)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
- localMediaPlayer.stop();
+ if (localMediaPlayer != null)
+ localMediaPlayer.stop();
if (AppEngine.getInstance().getContext() == null)
AppEngine.getInstance().setContext(AlarmAlertActivity.this); // 需要设置,否则会有空指针的异常
HashMap<String, Object> info = new HashMap<String, Object>();
info.put("channel_id", channelId);
info.put("channel_name", channelName);
info.put("program", program);
info.put("day", day);
AppEngine.getInstance().getAlarmHelper().notifyAlarmListeners(info);
AppEngine.getInstance().getAlarmHelper().removeAlarm(channelId, channelName, program, Integer.valueOf(day).intValue());
AlarmAlertActivity.this.finish();
}
}).create();
dialog.setCancelable(false);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener()
{
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_SEARCH)
return true;
else
return false;
}
});
dialog.show();
}
@Override
public void onDestroy()
{
super.onDestroy();
resetAllAlarms();
}
public Uri getDefaultRingtoneUri(int paramInt)
{
return RingtoneManager.getActualDefaultRingtoneUri(this, paramInt);
}
// 重新计算闹铃时间
private void resetAllAlarms()
{
if (AppEngine.getInstance().getContext() == null)
AppEngine.getInstance().setContext(AlarmAlertActivity.this);
AppEngine.getInstance().getAlarmHelper().resetAllAlarms();
}
}
| false | true | public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
final MediaPlayer localMediaPlayer = MediaPlayer.create(this, getDefaultRingtoneUri(4));
localMediaPlayer.setLooping(true);
localMediaPlayer.start();
final String channelId = getIntent().getStringExtra("channel_id");
final String channelName = getIntent().getStringExtra("channel_name");
final String program = getIntent().getStringExtra("program");
final String day = getIntent().getStringExtra("day");
AlertDialog dialog = new AlertDialog.Builder(AlarmAlertActivity.this).setIcon(R.drawable.clock)
.setTitle(channelName)
.setMessage(program)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
localMediaPlayer.stop();
if (AppEngine.getInstance().getContext() == null)
AppEngine.getInstance().setContext(AlarmAlertActivity.this); // 需要设置,否则会有空指针的异常
HashMap<String, Object> info = new HashMap<String, Object>();
info.put("channel_id", channelId);
info.put("channel_name", channelName);
info.put("program", program);
info.put("day", day);
AppEngine.getInstance().getAlarmHelper().notifyAlarmListeners(info);
AppEngine.getInstance().getAlarmHelper().removeAlarm(channelId, channelName, program, Integer.valueOf(day).intValue());
AlarmAlertActivity.this.finish();
}
}).create();
dialog.setCancelable(false);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener()
{
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_SEARCH)
return true;
else
return false;
}
});
dialog.show();
}
| public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
final MediaPlayer localMediaPlayer = MediaPlayer.create(this, getDefaultRingtoneUri(4));
if (localMediaPlayer != null)
{
localMediaPlayer.setLooping(true);
localMediaPlayer.start();
}
final String channelId = getIntent().getStringExtra("channel_id") == null ? "" : getIntent().getStringExtra("channel_id");
final String channelName = getIntent().getStringExtra("channel_name") == null ? "" : getIntent().getStringExtra("channel_name");
final String program = getIntent().getStringExtra("program") == null ? "" : getIntent().getStringExtra("program");
final String day = getIntent().getStringExtra("day") == null ? "1" : getIntent().getStringExtra("day");
AlertDialog dialog = new AlertDialog.Builder(AlarmAlertActivity.this).setIcon(R.drawable.clock)
.setTitle(channelName)
.setMessage(program)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
if (localMediaPlayer != null)
localMediaPlayer.stop();
if (AppEngine.getInstance().getContext() == null)
AppEngine.getInstance().setContext(AlarmAlertActivity.this); // 需要设置,否则会有空指针的异常
HashMap<String, Object> info = new HashMap<String, Object>();
info.put("channel_id", channelId);
info.put("channel_name", channelName);
info.put("program", program);
info.put("day", day);
AppEngine.getInstance().getAlarmHelper().notifyAlarmListeners(info);
AppEngine.getInstance().getAlarmHelper().removeAlarm(channelId, channelName, program, Integer.valueOf(day).intValue());
AlarmAlertActivity.this.finish();
}
}).create();
dialog.setCancelable(false);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener()
{
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_SEARCH)
return true;
else
return false;
}
});
dialog.show();
}
|
diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/SplitManager.java b/MyTracks/src/com/google/android/apps/mytracks/services/SplitManager.java
index 79533e20..321e8076 100644
--- a/MyTracks/src/com/google/android/apps/mytracks/services/SplitManager.java
+++ b/MyTracks/src/com/google/android/apps/mytracks/services/SplitManager.java
@@ -1,159 +1,160 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.util.UnitConversions;
import android.util.Log;
/**
* This class manages inserting time or distance splits.
*
* @author Sandor Dornbush
*/
public class SplitManager {
/**
* The frequency of splits.
*/
private int splitFrequency = 0;
/**
* The next distance when a split should be taken.
*/
private double nextSplitDistance = 0;
/**
* Splits executer.
*/
private PeriodicTaskExecuter splitExecuter = null;
private boolean metricUnits;
private final TrackRecordingService service;
public SplitManager(TrackRecordingService service) {
this.service = service;
}
/**
* Restores the manager.
*/
public void restore() {
if ((splitFrequency > 0) && (splitExecuter != null)) {
splitExecuter.scheduleTask(splitFrequency * 60000);
}
calculateNextSplit();
}
/**
* Shuts down the manager.
*/
public void shutdown() {
if (splitExecuter != null) {
splitExecuter.shutdown();
}
}
/**
* Calculates the next distance that a split should be inserted at.
*/
public void calculateNextSplit() {
// TODO: Decouple service from this class once and forever.
if (!service.isRecording()) {
return;
}
if (splitFrequency >= 0) {
nextSplitDistance = Double.MAX_VALUE;
Log.d(MyTracksConstants.TAG,
"SplitManager: Distance splits disabled.");
return;
}
double dist = service.getTripStatistics().getTotalDistance() / 1000;
if (!metricUnits) {
dist *= UnitConversions.KM_TO_MI;
}
// The index will be negative since the frequency is negative.
int index = (int) (dist / splitFrequency);
index -= 1;
nextSplitDistance = splitFrequency * index;
Log.d(MyTracksConstants.TAG,
"SplitManager: Next split distance: " + nextSplitDistance);
}
/**
* Updates split manager with new trip statistics.
*/
public void updateSplits() {
if (this.splitFrequency >= 0) {
return;
}
// Convert the distance in meters to km or mi.
double distance = service.getTripStatistics().getTotalDistance() / 1000.0;
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
}
if (distance > this.nextSplitDistance) {
service.insertStatisticsMarker(service.getLastLocation());
calculateNextSplit();
}
}
/**
* Sets the split frequency.
* < 0 Use the absolute value as a distance in the current measurement km
* or mi
* 0 Turn off splits
* > 0 Use the value as a time in minutes
* @param splitFrequency The frequency in time or distance
*/
public void setSplitFrequency(int splitFrequency) {
Log.d(MyTracksConstants.TAG,
"setSplitFrequency: splitFrequency = " + splitFrequency);
this.splitFrequency = splitFrequency;
// TODO: Decouple service from this class once and forever.
if (!service.isRecording()) {
return;
}
if (splitFrequency < 1) {
if (splitExecuter != null) {
splitExecuter.shutdown();
splitExecuter = null;
}
}
if (splitFrequency > 0) {
if (splitExecuter == null) {
TimeSplitTask splitter = new TimeSplitTask();
+ splitter.start();
splitExecuter = new PeriodicTaskExecuter(splitter, service);
}
splitExecuter.scheduleTask(splitFrequency * 60000);
} else {
// For distance based splits.
calculateNextSplit();
}
}
public void setMetricUnits(boolean metricUnits) {
this.metricUnits = metricUnits;
calculateNextSplit();
}
}
| true | true | public void setSplitFrequency(int splitFrequency) {
Log.d(MyTracksConstants.TAG,
"setSplitFrequency: splitFrequency = " + splitFrequency);
this.splitFrequency = splitFrequency;
// TODO: Decouple service from this class once and forever.
if (!service.isRecording()) {
return;
}
if (splitFrequency < 1) {
if (splitExecuter != null) {
splitExecuter.shutdown();
splitExecuter = null;
}
}
if (splitFrequency > 0) {
if (splitExecuter == null) {
TimeSplitTask splitter = new TimeSplitTask();
splitExecuter = new PeriodicTaskExecuter(splitter, service);
}
splitExecuter.scheduleTask(splitFrequency * 60000);
} else {
// For distance based splits.
calculateNextSplit();
}
}
| public void setSplitFrequency(int splitFrequency) {
Log.d(MyTracksConstants.TAG,
"setSplitFrequency: splitFrequency = " + splitFrequency);
this.splitFrequency = splitFrequency;
// TODO: Decouple service from this class once and forever.
if (!service.isRecording()) {
return;
}
if (splitFrequency < 1) {
if (splitExecuter != null) {
splitExecuter.shutdown();
splitExecuter = null;
}
}
if (splitFrequency > 0) {
if (splitExecuter == null) {
TimeSplitTask splitter = new TimeSplitTask();
splitter.start();
splitExecuter = new PeriodicTaskExecuter(splitter, service);
}
splitExecuter.scheduleTask(splitFrequency * 60000);
} else {
// For distance based splits.
calculateNextSplit();
}
}
|
diff --git a/src/graindcafe/tribu/Tribu.java b/src/graindcafe/tribu/Tribu.java
index b889b61..1864047 100644
--- a/src/graindcafe/tribu/Tribu.java
+++ b/src/graindcafe/tribu/Tribu.java
@@ -1,1014 +1,1014 @@
/*******************************************************************************
* Copyright or � or Copr. Quentin Godron (2011)
*
* [email protected]
*
* This software is a computer program whose purpose is to create zombie
* survival games on Bukkit's server.
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
******************************************************************************/
package graindcafe.tribu;
import graindcafe.tribu.Configuration.Constants;
import graindcafe.tribu.Configuration.TribuConfig;
import graindcafe.tribu.Executors.CmdDspawn;
import graindcafe.tribu.Executors.CmdIspawn;
import graindcafe.tribu.Executors.CmdTribu;
import graindcafe.tribu.Executors.CmdZspawn;
import graindcafe.tribu.Inventory.TribuInventory;
import graindcafe.tribu.Inventory.TribuTempInventory;
import graindcafe.tribu.Level.LevelFileLoader;
import graindcafe.tribu.Level.LevelSelector;
import graindcafe.tribu.Level.TribuLevel;
import graindcafe.tribu.Listeners.TribuBlockListener;
import graindcafe.tribu.Listeners.TribuEntityListener;
import graindcafe.tribu.Listeners.TribuPlayerListener;
import graindcafe.tribu.Listeners.TribuWorldListener;
import graindcafe.tribu.Rollback.ChunkMemory;
import graindcafe.tribu.TribuZombie.EntityTribuZombie;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import me.graindcafe.gls.DefaultLanguage;
import me.graindcafe.gls.Language;
import net.minecraft.server.EntityTypes;
import net.minecraft.server.EntityZombie;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.entity.Wolf;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
/**
* @author Graindcafe
*/
public class Tribu extends JavaPlugin {
public static String getExceptionMessage(final Exception e) {
String message = e.getLocalizedMessage() + "\n";
for (final StackTraceElement st : e.getStackTrace())
message += "[" + st.getFileName() + ":" + st.getLineNumber() + "] " + st.getClassName() + "->" + st.getMethodName() + "\n";
return message;
}
/**
* Send a message to a player or the console
*
* @param sender
* The one to send a message
* @param message
* The message
*/
public static void messagePlayer(final CommandSender sender, final String message) {
if (!message.isEmpty()) if (sender == null)
Logger.getLogger("Minecraft").info(ChatColor.stripColor(message));
else
sender.sendMessage(message);
}
private int aliveCount;
private TribuBlockListener blockListener;
private TribuConfig config;
private TribuEntityListener entityListener;
private TribuInventory inventorySave;
private boolean isRunning;
private Language language;
private TribuLevel level;
private LevelFileLoader levelLoader;
private LevelSelector levelSelector;
private Logger log;
private ChunkMemory memory;
private TribuPlayerListener playerListener;
private HashMap<Player, PlayerStats> players;
private Random rnd;
private LinkedList<PlayerStats> sortedStats;
private TribuSpawner spawner;
private HashMap<Player, Location> spawnPoint;
private SpawnTimer spawnTimer;
private HashMap<Player, TribuTempInventory> tempInventories;
private int waitingPlayers = -1;
private WaveStarter waveStarter;
private TribuWorldListener worldListener;
/**
* Add packages from config file to the level
*/
public void addDefaultPackages() {
if (level != null && config.DefaultPackages != null) for (final Package pck : config.DefaultPackages)
level.addPackage(pck);
}
/**
* Add a player to the game
*
* @param player
* player to add
*/
public void addPlayer(final Player player) {
if (player != null && !players.containsKey(player)) {
if (config.PlayersStoreInventory) {
inventorySave.addInventory(player);
player.getInventory().clear();
}
final PlayerStats stats = new PlayerStats(player);
players.put(player, stats);
sortedStats.add(stats);
messagePlayer(player, getLocale("Message.YouJoined"));
if (waitingPlayers != 0) {
waitingPlayers--;
if (waitingPlayers == 0) // No need to delay if everyone is
// playing
if (config.PluginModeServerExclusive)
startRunning();
else
startRunning(config.LevelStartDelay);
} else if (getLevel() != null && isRunning) {
player.teleport(level.getDeathSpawn());
messagePlayer(player, language.get("Message.GameInProgress"));
}
}
}
/**
* Add a player to the game in timeout seconds
*
* @param player
* Player to add
* @param timeout
* Time to wait in seconds
*/
public void addPlayer(final Player player, final double timeout) {
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
addPlayer(player);
}
}, Math.round(Constants.TicksBySecond * timeout));
}
/**
* Broadcast message to every players on the server
*
* @param message
* Message to broadcast
*/
public void broadcast(final String msg) {
if (msg.isEmpty()) getServer().broadcastMessage(msg);
}
/**
* Broadcast message to every players on the server after formating the
* given language node
*
* @param languageNode
* The language node to format
* @param params
* The arguments to pass to the language node
*/
public void broadcast(final String languageNode, final Object... params) {
broadcast(String.format(getLocale(languageNode), params));
}
/**
* Broadcast message to every players on the server with given permission
*
* @param message
* Message to broadcast
* @param permission
* Permission to have
*/
public void broadcast(final String message, final String permission) {
if (message.isEmpty()) getServer().broadcast(message, permission);
}
/**
* Broadcast message to every players on the server with the given
* permission after formating the given language node
*
* @param languageNode
* The language node to format
* @param params
* The arguments to pass to the language node
*/
public void broadcast(final String languageNode, final String permission, final Object... params) {
broadcast(String.format(getLocale(languageNode), params), permission);
}
public void checkAliveCount() {
// log.info("checking alive count " + aliveCount);
if (aliveCount == 0 && isRunning) {
messagePlayers(language.get("Message.ZombieHavePrevailed"));
messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber())));
stopRunning(true);
if (getPlayersCount() != 0) getLevelSelector().startVote(Constants.VoteDelay);
}
}
/**
* Get the current TribuConfig
*
* @return
*/
public TribuConfig config() {
return config;
}
/**
* Get the number of players that are not dead
*
* @return
*/
public int getAliveCount() {
return aliveCount;
}
public ChunkMemory getChunkMemory() {
return memory;
}
public TribuLevel getLevel() {
return level;
}
public LevelFileLoader getLevelLoader() {
return levelLoader;
}
public LevelSelector getLevelSelector() {
return levelSelector;
}
public String getLocale(final String key) {
return language.get(key);
}
public Player getNearestPlayer(final double x, final double y, final double z) {
return getNearestPlayer(new Location(level.getInitialSpawn().getWorld(), x, y, z));
}
/**
* Get the nearest player from a location
*
* @param location
* @return nearest player
*/
public Player getNearestPlayer(final Location location) {
Player minPlayer = null;
double minVal = Double.MAX_VALUE;
double d;
for (final Player p : players.keySet()) {
d = location.distanceSquared(p.getLocation());
if (minVal > d) {
minVal = d;
minPlayer = p;
}
}
return minPlayer;
}
public Set<Player> getPlayers() {
return players.keySet();
}
public int getPlayersCount() {
return players.size();
}
public Player getRandomPlayer() {
return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer();
}
public LinkedList<PlayerStats> getSortedStats() {
Collections.sort(sortedStats);
return sortedStats;
}
public TribuSpawner getSpawner() {
return spawner;
}
public SpawnTimer getSpawnTimer() {
return spawnTimer;
}
public PlayerStats getStats(final Player player) {
return players.get(player);
}
public WaveStarter getWaveStarter() {
return waveStarter;
}
/**
* Init default language and if there is a config the chosen language
*/
private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(Constants.languagesFolder);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedSubId", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.PlayerDied", ChatColor.LIGHT_PURPLE + "%s" + ChatColor.RED + " has died.");
put("Message.PlayerRevive", ChatColor.GREEN + "You have been revived.");
put("Message.PlayerDSpawnLeaveWarning", ChatColor.GOLD + "You cannot leave until a new round starts.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Message.Died", ChatColor.GRAY + "%s died.");
- put("Broadcast.GameStartingSoon", ChatColor.GRAY + "Game is starting in +" + ChatColor.RED + "%.0f" + ChatColor.GRAY + " seconds!");
+ put("Broadcast.GameStartingSoon", ChatColor.GRAY + "Game is starting in " + ChatColor.RED + "%.0f" + ChatColor.GRAY + " seconds!");
put("Broadcast.GameStarting", ChatColor.DARK_RED + "Fight!");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED
+ "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.CannotCopyLanguages", ChatColor.RED + "Cannot copy languages files.");
put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Prefix.Broadcast", "[Tribu] ");
put("Prefix.Message", "");
put("Prefix.Info", "[Tribu] ");
put("Prefix.Warning", "[Tribu] ");
put("Prefix.Severe", "[Tribu] ");
}
});
if (config != null) {
language = Language.init(config.PluginModeLanguage);
if (language.isLoaded()) LogWarning(language.get("Warning.LanguageFileMissing"));
if (language.isOutdated()) LogWarning(language.get("Warning.LanguageOutdated"));
LogInfo(String.format(language.get("Info.ChosenLanguage"), language.getName(), language.getAuthor()));
} else
language = new DefaultLanguage();
language.setPrefix("Message.", language.get("Prefix.Message"));
language.setPrefix("Broadcast.", language.get("Prefix.Broadcast"));
language.setPrefix("Info.", language.get("Prefix.Info"));
language.setPrefix("Warning.", language.get("Prefix.Warning"));
language.setPrefix("Severe.", language.get("Prefix.Severe"));
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
public boolean isAlive(final Player player) {
return players.get(player).isalive();
}
/**
* Check if Tribu is running and there is a level if it's server exclusive
* or world exclusive & in the good world or if it's near the initial spawn
* (radius "LevelClearZone")
*
* @param loc
* Location to check
* @return is inside level
*/
public boolean isInsideLevel(final Location loc) {
return isInsideLevel(loc, false);
}
/**
* Check if Tribu is running and there is a level if it's server exclusive
* or world exclusive & in the good world or if it's near the initial spawn
* (radius "LevelClearZone")
*
* @param loc
* Location to check
* @param dontCheckRunning
* Do not check if the plugin is running
* @return is inside level
*/
public boolean isInsideLevel(final Location loc, final boolean dontCheckRunning) {
if ((dontCheckRunning || isRunning) && level != null)
return config.PluginModeServerExclusive || loc.getWorld().equals(level.getInitialSpawn().getWorld()) && (config.PluginModeWorldExclusive || loc.distance(level.getInitialSpawn()) < config.LevelClearZone);
else
return false;
}
/**
* Is this player playing Tribu ?
*
* @param player
* @return Is this player playing Tribu ?
*/
public boolean isPlaying(final Player p) {
return players.containsKey(p);
}
/**
* Is the plugin running ? (not waiting for players but really running)
*
* @return Is the plugin running ?
*/
public boolean isRunning() {
return isRunning;
}
public void keepTempInv(final Player p, final ItemStack[] items) {
// log.info("Keep " + items.length + " items for " +
// p.getDisplayName());
tempInventories.put(p, new TribuTempInventory(p, items));
}
/**
* Load the custom config files, "per-world" and "per-level"
*/
protected void loadCustomConf() {
loadCustomConf(level.getName() + ".yml", level.getInitialSpawn().getWorld().getName() + ".yml");
}
protected void loadCustomConf(final String levelName, final String worldName) {
final TribuLevel level = getLevel();
if (level == null) return;
File worldFile = null, levelFile = null, worldDir, levelDir;
worldDir = new File(Constants.perWorldFolder);
levelDir = new File(Constants.perLevelFolder);
if (!levelDir.exists()) levelDir.mkdirs();
if (!worldDir.exists()) worldDir.mkdirs();
for (final File file : levelDir.listFiles())
if (file.getName().equalsIgnoreCase(levelName)) {
levelFile = file;
break;
}
for (final File file : worldDir.listFiles())
if (file.getName().equalsIgnoreCase(worldName)) {
worldFile = file;
break;
}
if (levelFile != null)
if (worldFile != null)
config = new TribuConfig(levelFile, new TribuConfig(worldFile));
else
config = new TribuConfig(levelFile);
else
config = new TribuConfig();
initLanguage();
if (config.PluginModeServerExclusive) for (final Player p : getServer().getOnlinePlayers())
this.addPlayer(p);
if (config.PluginModeWorldExclusive && level != null) for (final Player d : level.getInitialSpawn().getWorld().getPlayers())
this.addPlayer(d);
if (config.PluginModeAutoStart) startRunning();
}
public void LogInfo(final String message) {
log.info(message);
}
public void LogSevere(final String message) {
log.severe(message);
}
public void LogWarning(final String message) {
log.warning(message);
}
/**
* Send a message after formating the given languageNode with given
* arguments
*
* @param sender
* The one to send a message
* @param languageNode
* The language node to format
* @param params
* The arguments to pass to the language node
*/
public void messagePlayer(final CommandSender sender, final String languageNode, final Object... params) {
messagePlayer(sender, String.format(getLocale(languageNode), params));
}
/**
* Broadcast message to playing players
*
* @param msg
*/
public void messagePlayers(final String msg) {
if (!msg.isEmpty()) for (final Player p : players.keySet())
p.sendMessage(msg);
}
/**
* Broadcast message to playing players after formating the given language
* node
*
* @param languageNode
* The language node to format
* @param params
* The arguments to pass to the language node
*/
public void messagePlayers(final String languageNode, final Object... params) {
messagePlayers(String.format(getLocale(languageNode), params));
}
@Override
public void onDisable() {
inventorySave.restoreInventories();
players.clear();
sortedStats.clear();
memory.restoreAll();
stopRunning();
LogInfo(language.get("Info.Disable"));
}
@Override
public void onEnable() {
log = Logger.getLogger("Minecraft");
rnd = new Random();
final boolean mkdirs = Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar);
boolean langCopy = true;
for (final String name : Constants.languages) {
final InputStream fis = this.getClass().getResourceAsStream("/res/languages/" + name + ".yml");
FileOutputStream fos = null;
final File f = new File(Constants.languagesFolder + name + ".yml");
{
try {
fos = new FileOutputStream(f);
final byte[] buf = new byte[1024];
int i = 0;
if (f.canWrite() && fis.available() > 0) while ((i = fis.read(buf)) != -1)
fos.write(buf, 0, i);
} catch (final Exception e) {
e.printStackTrace();
langCopy = false;
} finally {
try {
if (fis != null) fis.close();
if (fos != null) fos.close();
} catch (final Exception e) {
}
}
}
}
try {
@SuppressWarnings("rawtypes")
final Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE };
final Method a = EntityTypes.class.getDeclaredMethod("a", args);
a.setAccessible(true);
a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893);
a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893);
} catch (final Exception e) {
setEnabled(false);
e.printStackTrace();
return;
}
// Before loading conf
players = new HashMap<Player, PlayerStats>();
// isRunning set to true to prevent start running at "loadCustomConf"
isRunning = true;
aliveCount = 0;
level = null;
// A language should be loaded BEFORE levelLoader uses
initLanguage();
levelLoader = new LevelFileLoader(this);
// The level loader have to be ready
reloadConf();
isRunning = false;
tempInventories = new HashMap<Player, TribuTempInventory>();
inventorySave = new TribuInventory();
spawnPoint = new HashMap<Player, Location>();
sortedStats = new LinkedList<PlayerStats>();
levelSelector = new LevelSelector(this);
spawner = new TribuSpawner(this);
spawnTimer = new SpawnTimer(this);
waveStarter = new WaveStarter(this);
// Create listeners
playerListener = new TribuPlayerListener(this);
entityListener = new TribuEntityListener(this);
blockListener = new TribuBlockListener(this);
worldListener = new TribuWorldListener(this);
memory = new ChunkMemory();
getServer().getPluginManager().registerEvents(playerListener, this);
getServer().getPluginManager().registerEvents(entityListener, this);
getServer().getPluginManager().registerEvents(blockListener, this);
getServer().getPluginManager().registerEvents(worldListener, this);
getCommand("dspawn").setExecutor(new CmdDspawn(this));
getCommand("zspawn").setExecutor(new CmdZspawn(this));
getCommand("ispawn").setExecutor(new CmdIspawn(this));
getCommand("tribu").setExecutor(new CmdTribu(this));
if (!mkdirs) LogSevere(getLocale("Severe.TribuCantMkdir"));
if (!langCopy) LogSevere(getLocale("Severe.CannotCopyLanguages"));
LogInfo(language.get("Info.Enable"));
if (config.PluginModeAutoStart) startRunning();
}
public void reloadConf() {
// Reload the main config file from disk
reloadConfig();
// Parse again the file
config = new TribuConfig(getConfig());
// Create the file if it doesn't exist
try {
getConfig().save(Constants.configFile);
} catch (final IOException e1) {
e1.printStackTrace();
}
// Before "loadCustom"
if (config.PluginModeDefaultLevel != "") {
final String worldName = levelLoader.getWorldName(config.PluginModeDefaultLevel);
this.loadCustomConf(config.PluginModeDefaultLevel, worldName);
setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel));
}
// After loading the level from main file
else
this.loadCustomConf();
}
/**
* Remove a player from the game
*
* @param player
*/
public void removePlayer(final Player player) {
if (player != null && players.containsKey(player)) {
if (isAlive(player)) aliveCount--;
if (!isRunning && waitingPlayers != -1 && waitingPlayers < config.LevelMinPlayers) waitingPlayers++;
sortedStats.remove(players.get(player));
inventorySave.restoreInventory(player);
players.remove(player);
Tribu.messagePlayer(player, getLocale("Message.YouLeft"));
if (player.isOnline() && spawnPoint.containsKey(player)) player.setBedSpawnLocation(spawnPoint.remove(player));
// check alive AFTER player remove
checkAliveCount();
// remove vote AFTER player remove
levelSelector.removeVote(player);
if (!player.isDead()) restoreInventory(player);
}
}
/**
* Set that the player spawn has been reseted and should be set it back when
* reviving
*
* @param p
* The player
* @param point
* The previous spawn
*/
public void resetedSpawnAdd(final Player p, final Location point) {
spawnPoint.put(p, point);
}
public void restoreInventory(final Player p) {
// log.info("Restore items for " + p.getDisplayName());
inventorySave.restoreInventory(p);
}
public void restoreTempInv(final Player p) {
// log.info("Restore items for " + p.getDisplayName());
if (tempInventories.containsKey(p)) tempInventories.remove(p).restore();
}
/**
* Revive a player
*
* @param player
*/
public void revivePlayer(final Player player) {
if (spawnPoint.containsKey(player)) player.setBedSpawnLocation(spawnPoint.remove(player));
players.get(player).revive();
if (config.WaveStartHealPlayers) player.setHealth(20);
if (config.WaveStartFeedPlayers) player.setFoodLevel(20);
restoreTempInv(player);
aliveCount++;
}
/**
* Revive all players
*
* @param teleportAll
* Teleport everyone or just dead people
*/
public void revivePlayers(final boolean teleportAll) {
aliveCount = 0;
for (final Player player : players.keySet()) {
revivePlayer(player);
if (isRunning && level != null && (teleportAll || !isAlive(player))) player.teleport(level.getInitialSpawn());
}
}
/**
* Mark a player as dead and do all necessary stuff
*
* @param player
*/
public void setDead(final Player player) {
if (players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
final PlayerStats p = players.get(player);
p.resetMoney();
p.subtractmoney(config.StatsOnPlayerDeathMoney);
p.subtractPoints(config.StatsOnPlayerDeathPoints);
p.msgStats();
messagePlayers("Message.Died", player.getName());
}
players.get(player).kill();
if (getLevel() != null && isRunning) checkAliveCount();
}
}
/**
* Set the current level
*
* @param level
*/
public void setLevel(final TribuLevel level) {
this.level = level;
this.loadCustomConf();
}
/**
* Start a new game
*
* @return if the game can start
*/
public boolean startRunning() {
if (waitingPlayers == -1) {
waitingPlayers = config.LevelMinPlayers - players.size();
if (waitingPlayers < 0) waitingPlayers = 0;
}
if (!isRunning && getLevel() != null && waitingPlayers == 0) {
// Before (next instruction) it will saves current default
// packages to the level, saving theses packages with the level
addDefaultPackages();
// Make sure no data is lost if server decides to die
// during a game and player forgot to /level save
if (!getLevelLoader().saveLevel(getLevel()))
LogWarning(language.get("Warning.UnableToSaveLevel"));
else
LogInfo(language.get("Info.LevelSaved"));
if (getLevel().getSpawns().isEmpty()) {
LogWarning(language.get("Warning.NoSpawns"));
return false;
}
isRunning = true;
if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive)
for (final LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE);
}
else
for (final LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities())
if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone && !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE);
if (config.PlayersRollback) {
// If there is a restoring operation currently, do it
// quickly
memory.getReady();
memory.startCapturing();
// Pre-cache level
memory.add(level.getInitialSpawn().getChunk());
memory.add(level.getDeathSpawn().getChunk());
for (final Location l : level.getZombieSpawns())
memory.add(l.getChunk());
}
getLevel().initSigns();
sortedStats.clear();
for (final PlayerStats stat : players.values()) {
stat.resetPoints();
stat.resetMoney();
sortedStats.add(stat);
}
getWaveStarter().resetWave();
revivePlayers(true);
getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay);
}
return true;
}
/**
* Start the game in n seconds
*
* @param timeout
* Delay in seconds
*/
public void startRunning(final float timeout) {
final float step = (1f - timeout % 1);
final Stack<Float> broadcastTime = new Stack<Float>();
if (timeout > 2f) broadcastTime.push(2f);
if (timeout > 3f) broadcastTime.push(3f);
if (timeout > 4f) broadcastTime.push(4f);
float i = 5;
while (timeout > i) {
broadcastTime.push(i);
i += 5f;
}
broadcastTime.push(timeout);
final int taskId = getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
private float counter = timeout;
@Override
public void run() {
if (counter <= 0f)
startRunning();
else if (broadcastTime.isEmpty())
messagePlayers(getLocale("Broadcast.GameStarting"));
else if (broadcastTime.peek() >= counter) messagePlayers("Broadcast.GameStartingSoon", broadcastTime.pop());
counter -= step;
}
}, 0, Math.round(step * Constants.TicksBySecond));
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
getServer().getScheduler().cancelTask(taskId);
}
}, (long) (Math.ceil(timeout * Constants.TicksBySecond) + 1));
}
/**
* End the game
*/
public void stopRunning() {
stopRunning(false);
}
public void stopRunning(final boolean rerun) {
getLevelSelector().cancelVote();
if (isRunning) {
isRunning = false;
getSpawnTimer().stop();
getWaveStarter().cancelWave();
getSpawner().clearZombies();
if (config.PlayersRollback) memory.startRestoring(this, config.AdvancedRestoringSpeed);
level.finishSigns();
// Teleports all players to spawn when game ends
for (final Player p : players.keySet())
p.teleport(level.getInitialSpawn());
if (!rerun) {
if (config.PlayersStoreInventory) inventorySave.restoreInventories();
if (!config.PluginModeServerExclusive && !config.PluginModeWorldExclusive) players.clear();
}
waitingPlayers = -1;
}
}
}
| true | true | private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(Constants.languagesFolder);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedSubId", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.PlayerDied", ChatColor.LIGHT_PURPLE + "%s" + ChatColor.RED + " has died.");
put("Message.PlayerRevive", ChatColor.GREEN + "You have been revived.");
put("Message.PlayerDSpawnLeaveWarning", ChatColor.GOLD + "You cannot leave until a new round starts.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Message.Died", ChatColor.GRAY + "%s died.");
put("Broadcast.GameStartingSoon", ChatColor.GRAY + "Game is starting in +" + ChatColor.RED + "%.0f" + ChatColor.GRAY + " seconds!");
put("Broadcast.GameStarting", ChatColor.DARK_RED + "Fight!");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED
+ "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.CannotCopyLanguages", ChatColor.RED + "Cannot copy languages files.");
put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Prefix.Broadcast", "[Tribu] ");
put("Prefix.Message", "");
put("Prefix.Info", "[Tribu] ");
put("Prefix.Warning", "[Tribu] ");
put("Prefix.Severe", "[Tribu] ");
}
});
if (config != null) {
language = Language.init(config.PluginModeLanguage);
if (language.isLoaded()) LogWarning(language.get("Warning.LanguageFileMissing"));
if (language.isOutdated()) LogWarning(language.get("Warning.LanguageOutdated"));
LogInfo(String.format(language.get("Info.ChosenLanguage"), language.getName(), language.getAuthor()));
} else
language = new DefaultLanguage();
language.setPrefix("Message.", language.get("Prefix.Message"));
language.setPrefix("Broadcast.", language.get("Prefix.Broadcast"));
language.setPrefix("Info.", language.get("Prefix.Info"));
language.setPrefix("Warning.", language.get("Prefix.Warning"));
language.setPrefix("Severe.", language.get("Prefix.Severe"));
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
| private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(Constants.languagesFolder);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedSubId", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.PlayerDied", ChatColor.LIGHT_PURPLE + "%s" + ChatColor.RED + " has died.");
put("Message.PlayerRevive", ChatColor.GREEN + "You have been revived.");
put("Message.PlayerDSpawnLeaveWarning", ChatColor.GOLD + "You cannot leave until a new round starts.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Message.Died", ChatColor.GRAY + "%s died.");
put("Broadcast.GameStartingSoon", ChatColor.GRAY + "Game is starting in " + ChatColor.RED + "%.0f" + ChatColor.GRAY + " seconds!");
put("Broadcast.GameStarting", ChatColor.DARK_RED + "Fight!");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED
+ "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.CannotCopyLanguages", ChatColor.RED + "Cannot copy languages files.");
put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Prefix.Broadcast", "[Tribu] ");
put("Prefix.Message", "");
put("Prefix.Info", "[Tribu] ");
put("Prefix.Warning", "[Tribu] ");
put("Prefix.Severe", "[Tribu] ");
}
});
if (config != null) {
language = Language.init(config.PluginModeLanguage);
if (language.isLoaded()) LogWarning(language.get("Warning.LanguageFileMissing"));
if (language.isOutdated()) LogWarning(language.get("Warning.LanguageOutdated"));
LogInfo(String.format(language.get("Info.ChosenLanguage"), language.getName(), language.getAuthor()));
} else
language = new DefaultLanguage();
language.setPrefix("Message.", language.get("Prefix.Message"));
language.setPrefix("Broadcast.", language.get("Prefix.Broadcast"));
language.setPrefix("Info.", language.get("Prefix.Info"));
language.setPrefix("Warning.", language.get("Prefix.Warning"));
language.setPrefix("Severe.", language.get("Prefix.Severe"));
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
|
diff --git a/src/main/java/cc/kune/wave/client/kspecific/WindowKuneWrapper.java b/src/main/java/cc/kune/wave/client/kspecific/WindowKuneWrapper.java
index 87f2fa396..fc3912ede 100644
--- a/src/main/java/cc/kune/wave/client/kspecific/WindowKuneWrapper.java
+++ b/src/main/java/cc/kune/wave/client/kspecific/WindowKuneWrapper.java
@@ -1,139 +1,140 @@
/*
*
* Copyright (C) 2007-2012 The kune development team (see CREDITS for details)
* This file is part of kune.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.kune.wave.client.kspecific;
import org.waveprotocol.wave.client.common.util.WindowConfirmCallback;
import org.waveprotocol.wave.client.common.util.WindowPromptCallback;
import org.waveprotocol.wave.client.common.util.WindowWrapper;
import cc.kune.common.client.notify.NotifyUser;
import cc.kune.common.shared.i18n.I18n;
import cc.kune.common.shared.utils.SimpleResponseCallback;
import cc.kune.core.client.ui.dialogs.PromptTopDialog;
import cc.kune.core.client.ui.dialogs.PromptTopDialog.Builder;
import cc.kune.core.client.ui.dialogs.PromptTopDialog.OnEnter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
/**
* The Class WindowKuneWrapper.
*/
public class WindowKuneWrapper implements WindowWrapper {
/** The Constant WINDOW_PROMPT_ID. */
public static final String WINDOW_PROMPT_ID = "k-window-prompt-id";
private WindowPromptCallback callback;
private PromptTopDialog diag;
/*
* (non-Javadoc)
*
* @see
* org.waveprotocol.box.webclient.client.WindowWrapper#alert(java.lang.String)
*/
@Override
public void alert(final String message) {
NotifyUser.showAlertMessage(I18n.t("Warning"), message);
}
/*
* (non-Javadoc)
*
* @see
* org.waveprotocol.wave.client.common.util.WindowWrapper#confirm(java.lang
* .String, org.waveprotocol.wave.client.common.util.WindowConfirmCallback)
*/
@Override
public void confirm(final String msg, final WindowConfirmCallback callback) {
NotifyUser.askConfirmation(I18n.t("Confirm"), msg, new SimpleResponseCallback() {
@Override
public void onCancel() {
callback.onCancel();
}
@Override
public void onSuccess() {
callback.onOk();
}
});
}
/**
* Do action.
*
* @param callback
* the callback
*/
protected void doPromptAction() {
callback.onReturn(diag.getTextFieldValue());
diag.hide();
}
/*
* (non-Javadoc)
*
* @see
* org.waveprotocol.wave.client.common.util.WindowWrapper#prompt(java.lang
* .String, java.lang.String,
* org.waveprotocol.wave.client.common.util.WindowPromptCallback)
*/
@Override
public void prompt(final String msg, final String value, final WindowPromptCallback callback) {
this.callback = callback;
if (diag == null) {
final Builder builder = new PromptTopDialog.Builder(WINDOW_PROMPT_ID, msg, false, true,
I18n.getDirection(), new OnEnter() {
@Override
public void onEnter() {
doPromptAction();
}
});
builder.firstButtonTitle(I18n.t("Ok"));
builder.sndButtonTitle(I18n.t("Cancel"));
+ builder.width("220px");
builder.tabIndexStart(1);
diag = builder.build();
diag.getFirstBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doPromptAction();
}
});
diag.getSecondBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
diag.hide();
}
});
diag.setFirstBtnTabIndex(1);
diag.setSecondBtnTabIndex(2);
diag.setTextFieldSelectOnFocus(true);
}
diag.setText(msg, I18n.getDirection());
diag.clearTextFieldValue();
diag.showCentered();
diag.setTextFieldValue(value);
diag.setTextFieldFocus();
}
}
| true | true | public void prompt(final String msg, final String value, final WindowPromptCallback callback) {
this.callback = callback;
if (diag == null) {
final Builder builder = new PromptTopDialog.Builder(WINDOW_PROMPT_ID, msg, false, true,
I18n.getDirection(), new OnEnter() {
@Override
public void onEnter() {
doPromptAction();
}
});
builder.firstButtonTitle(I18n.t("Ok"));
builder.sndButtonTitle(I18n.t("Cancel"));
builder.tabIndexStart(1);
diag = builder.build();
diag.getFirstBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doPromptAction();
}
});
diag.getSecondBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
diag.hide();
}
});
diag.setFirstBtnTabIndex(1);
diag.setSecondBtnTabIndex(2);
diag.setTextFieldSelectOnFocus(true);
}
diag.setText(msg, I18n.getDirection());
diag.clearTextFieldValue();
diag.showCentered();
diag.setTextFieldValue(value);
diag.setTextFieldFocus();
}
| public void prompt(final String msg, final String value, final WindowPromptCallback callback) {
this.callback = callback;
if (diag == null) {
final Builder builder = new PromptTopDialog.Builder(WINDOW_PROMPT_ID, msg, false, true,
I18n.getDirection(), new OnEnter() {
@Override
public void onEnter() {
doPromptAction();
}
});
builder.firstButtonTitle(I18n.t("Ok"));
builder.sndButtonTitle(I18n.t("Cancel"));
builder.width("220px");
builder.tabIndexStart(1);
diag = builder.build();
diag.getFirstBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doPromptAction();
}
});
diag.getSecondBtn().addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
diag.hide();
}
});
diag.setFirstBtnTabIndex(1);
diag.setSecondBtnTabIndex(2);
diag.setTextFieldSelectOnFocus(true);
}
diag.setText(msg, I18n.getDirection());
diag.clearTextFieldValue();
diag.showCentered();
diag.setTextFieldValue(value);
diag.setTextFieldFocus();
}
|
diff --git a/src/org/klnusbaum/udj/ArtistsDisplayFragment.java b/src/org/klnusbaum/udj/ArtistsDisplayFragment.java
index 6b17a2c..816c7a4 100644
--- a/src/org/klnusbaum/udj/ArtistsDisplayFragment.java
+++ b/src/org/klnusbaum/udj/ArtistsDisplayFragment.java
@@ -1,133 +1,137 @@
/**
* Copyright 2011 Kurtis L. Nusbaum
*
* This file is part of UDJ.
*
* UDJ 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.
*
* UDJ 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 UDJ. If not, see <http://www.gnu.org/licenses/>.
*/
package org.klnusbaum.udj;
import android.accounts.Account;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.content.Intent;
import android.app.SearchManager;
import android.widget.ListView;
import android.util.Log;
import android.app.Activity;
import android.accounts.Account;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.app.ListFragment;
import java.util.List;
public class ArtistsDisplayFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<ArtistsLoader.ArtistsResult>
{
private static final int ARTISTS_LOADER_TAG = 0;
private static final String TAG = "ArtistsDisplayFragment";
private int previousVisiblePosition;
private int previousVisibleIndex;
private List<String> currentArtistsList;
//private ArtistsAdapter artistsAdapter;
private ArrayAdapter<String> artistsAdapter;
private Account getAccount(){
return (Account)getArguments().getParcelable(Constants.ACCOUNT_EXTRA);
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Log.d(TAG, "Attaching artist view");
artistsAdapter =
new ArrayAdapter<String>(getActivity(), R.layout.artist_list_item, R.id.artist_name);
getLoaderManager().initLoader(ARTISTS_LOADER_TAG, null, this);
setListAdapter(artistsAdapter);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setEmptyText(getActivity().getString(R.string.no_artists));
setListShown(false);
getListView().setTextFilterEnabled(true);
}
public Loader<ArtistsLoader.ArtistsResult> onCreateLoader(
int id, Bundle args)
{
Log.d(TAG, "In creation of loader");
if(id == ARTISTS_LOADER_TAG){
return new ArtistsLoader(getActivity(), getAccount());
}
return null;
}
public void onLoadFinished(
Loader<ArtistsLoader.ArtistsResult> loader,
ArtistsLoader.ArtistsResult data)
{
Log.d(TAG, "In loader finshed");
if(data.error == ArtistsLoader.ArtistsError.NO_ERROR){
if(currentArtistsList == null || !currentArtistsList.equals(data.res)){
Log.d(TAG, "Changing artist list");
currentArtistsList = data.res;
artistsAdapter.clear();
- artistsAdapter.addAll(data.res);
+ //Add all not available until API 11, oh well
+ //artistsAdapter.addAll(data.res);
+ for(String artist : data.res){
+ artistsAdapter.add(artist);
+ }
}
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_INACTIVE_ERROR){
Utils.handleInactivePlayer(getActivity(), getAccount());
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_AUTH_ERROR){
//TODO REAUTH AND TRY AGAIN
}
if(isResumed()){
setListShown(true);
}
else if(isVisible()){
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<ArtistsLoader.ArtistsResult> loader){
Log.d(TAG, "Loader Was reset");
setListAdapter(null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
Log.d(TAG, "In on list item clicked");
final String artist = (String)artistsAdapter.getItem(position);
Intent artistIntent = new Intent(Intent.ACTION_SEARCH);
artistIntent.setClass(getActivity(), ArtistSearchActivity.class);
artistIntent.putExtra(SearchManager.QUERY, artist);
startActivityForResult(artistIntent, 0);
}
}
| true | true | public void onLoadFinished(
Loader<ArtistsLoader.ArtistsResult> loader,
ArtistsLoader.ArtistsResult data)
{
Log.d(TAG, "In loader finshed");
if(data.error == ArtistsLoader.ArtistsError.NO_ERROR){
if(currentArtistsList == null || !currentArtistsList.equals(data.res)){
Log.d(TAG, "Changing artist list");
currentArtistsList = data.res;
artistsAdapter.clear();
artistsAdapter.addAll(data.res);
}
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_INACTIVE_ERROR){
Utils.handleInactivePlayer(getActivity(), getAccount());
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_AUTH_ERROR){
//TODO REAUTH AND TRY AGAIN
}
if(isResumed()){
setListShown(true);
}
else if(isVisible()){
setListShownNoAnimation(true);
}
}
| public void onLoadFinished(
Loader<ArtistsLoader.ArtistsResult> loader,
ArtistsLoader.ArtistsResult data)
{
Log.d(TAG, "In loader finshed");
if(data.error == ArtistsLoader.ArtistsError.NO_ERROR){
if(currentArtistsList == null || !currentArtistsList.equals(data.res)){
Log.d(TAG, "Changing artist list");
currentArtistsList = data.res;
artistsAdapter.clear();
//Add all not available until API 11, oh well
//artistsAdapter.addAll(data.res);
for(String artist : data.res){
artistsAdapter.add(artist);
}
}
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_INACTIVE_ERROR){
Utils.handleInactivePlayer(getActivity(), getAccount());
}
else if(data.error == ArtistsLoader.ArtistsError.PLAYER_AUTH_ERROR){
//TODO REAUTH AND TRY AGAIN
}
if(isResumed()){
setListShown(true);
}
else if(isVisible()){
setListShownNoAnimation(true);
}
}
|
diff --git a/general/src/test/java/org/qi4j/library/general/model/PersonTest.java b/general/src/test/java/org/qi4j/library/general/model/PersonTest.java
index 34b324479..8a0cff221 100755
--- a/general/src/test/java/org/qi4j/library/general/model/PersonTest.java
+++ b/general/src/test/java/org/qi4j/library/general/model/PersonTest.java
@@ -1,43 +1,43 @@
/*
* Copyright (c) 2007, Sianny Halim. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.library.general.model;
import junit.framework.Assert;
import org.qi4j.api.Composite;
import org.qi4j.api.CompositeBuilder;
import static org.qi4j.api.annotation.ParameterValue.parameter;
public class PersonTest extends AbstractTest
{
public void testNewPerson() throws Exception
{
CompositeBuilder<PersonComposite> builder = builderFactory.newCompositeBuilder( PersonComposite.class );
- builder.newMixin( Person.class, parameter( "firstName", "Sianny"), parameter("lastName", "Halim"));
+ builder.properties( Person.class, parameter( "firstName", "Sianny"), parameter("lastName", "Halim"));
PersonComposite person = builder.newInstance();
String firstName = "Sianny";
String lastName = "Halim";
person.setFirstName( firstName );
person.setLastName( lastName );
person.setGender( GenderType.female );
Assert.assertEquals( firstName, person.getFirstName() );
Assert.assertEquals( lastName, person.getLastName() );
Assert.assertEquals( GenderType.female, person.getGender() );
}
private interface PersonComposite extends Person, Composite
{
}
}
| true | true | public void testNewPerson() throws Exception
{
CompositeBuilder<PersonComposite> builder = builderFactory.newCompositeBuilder( PersonComposite.class );
builder.newMixin( Person.class, parameter( "firstName", "Sianny"), parameter("lastName", "Halim"));
PersonComposite person = builder.newInstance();
String firstName = "Sianny";
String lastName = "Halim";
person.setFirstName( firstName );
person.setLastName( lastName );
person.setGender( GenderType.female );
Assert.assertEquals( firstName, person.getFirstName() );
Assert.assertEquals( lastName, person.getLastName() );
Assert.assertEquals( GenderType.female, person.getGender() );
}
| public void testNewPerson() throws Exception
{
CompositeBuilder<PersonComposite> builder = builderFactory.newCompositeBuilder( PersonComposite.class );
builder.properties( Person.class, parameter( "firstName", "Sianny"), parameter("lastName", "Halim"));
PersonComposite person = builder.newInstance();
String firstName = "Sianny";
String lastName = "Halim";
person.setFirstName( firstName );
person.setLastName( lastName );
person.setGender( GenderType.female );
Assert.assertEquals( firstName, person.getFirstName() );
Assert.assertEquals( lastName, person.getLastName() );
Assert.assertEquals( GenderType.female, person.getGender() );
}
|
diff --git a/src/main/java/net/krinsoft/chat/commands/MuteCommand.java b/src/main/java/net/krinsoft/chat/commands/MuteCommand.java
index e3c0972..0b371d7 100644
--- a/src/main/java/net/krinsoft/chat/commands/MuteCommand.java
+++ b/src/main/java/net/krinsoft/chat/commands/MuteCommand.java
@@ -1,51 +1,53 @@
package net.krinsoft.chat.commands;
import net.krinsoft.chat.ChatCore;
import net.krinsoft.chat.api.Target;
import net.krinsoft.chat.targets.Channel;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* @author krinsdeath
*/
public class MuteCommand extends ChatSuiteCommand {
public MuteCommand(ChatCore instance) {
super(instance);
setName("ChatSuite: User Mute");
setCommandUsage("/mute [target]");
setArgRange(1, 1);
addKey("chatsuite mute");
addKey("chat mute");
addKey("mute");
setPermission("chatsuite.mute", "Prevents the specified target from sending messages.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
Target target = plugin.getChannelManager().getChannel(args.get(0));
if (target == null) {
target = plugin.getPlayerManager().getPlayer(args.get(0));
if (target == null) {
if (args.get(0).startsWith("c:")) {
target = plugin.getChannelManager().getChannel(args.get(0).split(":")[1]);
} else if (args.get(0).startsWith("p:")) {
target = plugin.getPlayerManager().getPlayer(args.get(0).split(":")[1]);
} else {
target = null;
}
}
}
if (target != null) {
target.toggleMute();
+ target.persist();
+ plugin.getPlayerManager().saveConfig();
sender.sendMessage(ChatColor.GRAY + "You " + (target.isMuted() ? "" : "un") + "muted the " + (target instanceof Channel ? "channel " : "player ") + ChatColor.RED + target.getName() + ChatColor.GRAY + ".");
} else {
sender.sendMessage(ChatColor.RED + "No such player or channel.");
}
}
}
| true | true | public void runCommand(CommandSender sender, List<String> args) {
Target target = plugin.getChannelManager().getChannel(args.get(0));
if (target == null) {
target = plugin.getPlayerManager().getPlayer(args.get(0));
if (target == null) {
if (args.get(0).startsWith("c:")) {
target = plugin.getChannelManager().getChannel(args.get(0).split(":")[1]);
} else if (args.get(0).startsWith("p:")) {
target = plugin.getPlayerManager().getPlayer(args.get(0).split(":")[1]);
} else {
target = null;
}
}
}
if (target != null) {
target.toggleMute();
sender.sendMessage(ChatColor.GRAY + "You " + (target.isMuted() ? "" : "un") + "muted the " + (target instanceof Channel ? "channel " : "player ") + ChatColor.RED + target.getName() + ChatColor.GRAY + ".");
} else {
sender.sendMessage(ChatColor.RED + "No such player or channel.");
}
}
| public void runCommand(CommandSender sender, List<String> args) {
Target target = plugin.getChannelManager().getChannel(args.get(0));
if (target == null) {
target = plugin.getPlayerManager().getPlayer(args.get(0));
if (target == null) {
if (args.get(0).startsWith("c:")) {
target = plugin.getChannelManager().getChannel(args.get(0).split(":")[1]);
} else if (args.get(0).startsWith("p:")) {
target = plugin.getPlayerManager().getPlayer(args.get(0).split(":")[1]);
} else {
target = null;
}
}
}
if (target != null) {
target.toggleMute();
target.persist();
plugin.getPlayerManager().saveConfig();
sender.sendMessage(ChatColor.GRAY + "You " + (target.isMuted() ? "" : "un") + "muted the " + (target instanceof Channel ? "channel " : "player ") + ChatColor.RED + target.getName() + ChatColor.GRAY + ".");
} else {
sender.sendMessage(ChatColor.RED + "No such player or channel.");
}
}
|
diff --git a/src/com/turt2live/antishare/ASListener.java b/src/com/turt2live/antishare/ASListener.java
index f6bb9b94..3cf3bb9f 100644
--- a/src/com/turt2live/antishare/ASListener.java
+++ b/src/com/turt2live/antishare/ASListener.java
@@ -1,1378 +1,1380 @@
package com.turt2live.antishare;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BrewingStand;
import org.bukkit.block.Chest;
import org.bukkit.block.Furnace;
import org.bukkit.block.Jukebox;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.PoweredMinecart;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.entity.ThrownExpBottle;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import com.turt2live.antishare.money.Tender.TenderType;
import com.turt2live.antishare.notification.Alert.AlertTrigger;
import com.turt2live.antishare.notification.Alert.AlertType;
import com.turt2live.antishare.notification.MessageFactory;
import com.turt2live.antishare.permissions.PermissionNodes;
import com.turt2live.antishare.regions.ASRegion;
import com.turt2live.antishare.storage.PerWorldConfig;
import com.turt2live.antishare.storage.PerWorldConfig.ListType;
/**
* The core listener - Listens to all events needed by AntiShare and handles them
*
* @author turt2live
*/
public class ASListener implements Listener {
private AntiShare plugin = AntiShare.getInstance();
private ConcurrentHashMap<World, PerWorldConfig> config = new ConcurrentHashMap<World, PerWorldConfig>();
private boolean hasMobCatcher = false;
/**
* Creates a new Listener
*/
public ASListener(){
reload();
}
/**
* Reloads lists
*/
public void reload(){
config.clear();
for(World world : Bukkit.getWorlds()){
config.put(world, new PerWorldConfig(world));
}
hasMobCatcher = plugin.getServer().getPluginManager().getPlugin("MobCatcher") != null;
}
/**
* Prints out each world to the writer
*
* @param out the writer
* @throws IOException for internal handling
*/
public void print(BufferedWriter out) throws IOException{
for(World world : config.keySet()){
out.write("## WORLD: " + world.getName() + " \r\n");
config.get(world).print(out);
}
}
/**
* Gets the configuration for the world
*
* @param world the world
* @return the configuration
*/
public PerWorldConfig getConfig(World world){
return config.get(world);
}
// ################# World Load
@EventHandler
public void onWorldLoad(WorldLoadEvent event){
World world = event.getWorld();
config.put(world, new PerWorldConfig(world));
}
// ################# World Unload
@EventHandler
public void onWorldUnload(WorldUnloadEvent event){
if(event.isCancelled())
return;
World world = event.getWorld();
config.remove(world);
}
// ################# Block Break
@EventHandler (priority = EventPriority.LOWEST)
public void onBlockBreak(BlockBreakEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Block block = event.getBlock();
AlertType type = AlertType.ILLEGAL;
boolean special = false;
boolean region = false;
Boolean drops = null;
+ boolean deny = false;
AlertType specialType = AlertType.LEGAL;
String blockGM = "Unknown";
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(block.getWorld()).isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}
// Check creative/survival blocks
if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){
GameMode blockGamemode = plugin.getBlockManager().getType(block);
if(blockGamemode != null){
blockGM = blockGamemode.name().toLowerCase();
String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative";
if(player.getGameMode() != blockGamemode){
special = true;
- boolean deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny");
+ deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny");
drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops");
if(deny){
specialType = AlertType.ILLEGAL;
}
}
}
}
// Check regions
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){
ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation());
ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation());
if(playerRegion != blockRegion){
special = true;
region = true;
specialType = AlertType.ILLEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){
event.setCancelled(true);
}else{
plugin.getBlockManager().removeBlock(block);
}
// Alert
if(special){
if(region){
if(specialType == AlertType.ILLEGAL){
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region.";
String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region";
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK);
}
}else{
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break");
MessageFactory factory = new MessageFactory(specialPlayerMessage);
factory.insert(block, player, block.getWorld(), blockGM.equalsIgnoreCase("creative") ? TenderType.CREATIVE_BLOCK : TenderType.SURVIVAL_BLOCK);
specialPlayerMessage = factory.toString();
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK));
}
}else{
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String playerMessage = plugin.getMessage("blocked-action.break-block");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.BLOCK_BREAK);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK);
}
// Handle drops
- if(drops != null){
+ if(drops != null && !deny && special){
if(drops){
- if(event.isCancelled()){
- plugin.getBlockManager().removeBlock(block);
- block.breakNaturally();
- }
+ plugin.getBlockManager().removeBlock(block);
+ block.breakNaturally();
+ }else{
+ plugin.getBlockManager().removeBlock(block);
+ block.setType(Material.AIR);
}
}
// Check for 'attached' blocks and internal inventories
if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING) && !event.isCancelled()){
// Check inventories
if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){
if(block.getState() instanceof Chest){
Chest state = (Chest) block.getState();
state.getBlockInventory().clear();
}else if(block.getState() instanceof Jukebox){
Jukebox state = (Jukebox) block.getState();
state.setPlaying(null);
}else if(block.getState() instanceof Furnace){
Furnace state = (Furnace) block.getState();
state.getInventory().clear();
}else if(block.getState() instanceof BrewingStand){
BrewingStand state = (BrewingStand) block.getState();
state.getInventory().clear();
}
}
// Check for attached blocks
if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){
for(BlockFace face : BlockFace.values()){
Block rel = block.getRelative(face);
if(ASUtils.isDroppedOnBreak(rel, block)){
plugin.getBlockManager().removeBlock(rel);
rel.setType(Material.AIR);
}
}
}
}
}
// ################# Block Place
@EventHandler (priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Block block = event.getBlock();
AlertType type = AlertType.ILLEGAL;
boolean region = false;
// Sanity check
if(block.getType() == Material.AIR){
return;
}
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_PLACE, block.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(block, ListType.BLOCK_PLACE)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(block.getWorld()).isBlocked(block, ListType.BLOCK_PLACE)){
type = AlertType.LEGAL;
}
}
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_PLACE)){
ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation());
ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation());
if(playerRegion != blockRegion){
type = AlertType.ILLEGAL;
region = true;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}else{
// Handle block place for tracker
if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){
plugin.getBlockManager().addBlock(player.getGameMode(), block);
}
}
// Alert
if(region){
if(type == AlertType.ILLEGAL){
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to place " : " placed ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region.";
String playerMessage = ChatColor.RED + "You cannot place blocks in another region!";
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_PLACE);
}
}else{
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to place " : " placed ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String playerMessage = plugin.getMessage("blocked-action.place-block");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.BLOCK_PLACE);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_PLACE);
}
}
// ################# Player Interact Block
@EventHandler (priority = EventPriority.LOWEST)
public void onInteract(PlayerInteractEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Action action = event.getAction();
AlertType type = AlertType.LEGAL;
String message = "no message";
String playerMessage = "no message";
AlertTrigger trigger = AlertTrigger.RIGHT_CLICK;
// Check for AntiShare tool
if(plugin.getPermissions().has(player, PermissionNodes.TOOL_USE) && player.getItemInHand() != null
&& (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK)){
if(player.getItemInHand().getType() == AntiShare.ANTISHARE_TOOL){
String blockname = block.getType().name().replaceAll("_", " ").toLowerCase();
String gamemode = (plugin.getBlockManager().getType(block) != null ? plugin.getBlockManager().getType(block).name() : "natural").toLowerCase();
ASUtils.sendToPlayer(player, "That " + ChatColor.YELLOW + blockname + ChatColor.WHITE + " is a " + ChatColor.YELLOW + gamemode + ChatColor.WHITE + " block.");
// Cancel and stop the check
event.setCancelled(true);
return;
}
}
// Right click list
if(action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK){
// Check if they should be blocked
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(asregion.getConfig().isBlocked(block, ListType.RIGHT_CLICK)){
type = AlertType.ILLEGAL;
}
}else{
if(config.get(block.getWorld()).isBlocked(block, ListType.RIGHT_CLICK)){
type = AlertType.ILLEGAL;
}
}
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, block.getWorld())){
type = AlertType.LEGAL;
}
// Set messages
message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
playerMessage = plugin.getMessage("blocked-action.right-click");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.RIGHT_CLICK);
playerMessage = factory.toString();
}
// If this event is triggered as legal from the right click, check use lists
if(type == AlertType.LEGAL){
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(asregion.getConfig().isBlocked(block, ListType.USE)){
type = AlertType.ILLEGAL;
}
}else{
if(config.get(block.getWorld()).isBlocked(block, ListType.USE)){
type = AlertType.ILLEGAL;
}
}
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, block.getWorld())){
type = AlertType.LEGAL;
}
// Set messages
message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
playerMessage = plugin.getMessage("blocked-action.right-click");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.RIGHT_CLICK);
playerMessage = factory.toString();
}
// If the event is triggered as legal from the use lists, check the player's item in hand
if(type == AlertType.LEGAL && action == Action.RIGHT_CLICK_BLOCK && player.getItemInHand() != null){
// Check if they should be blocked
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(asregion.getConfig().isBlocked(player.getItemInHand().getType(), ListType.USE)){
type = AlertType.ILLEGAL;
}
}else{
if(config.get(block.getWorld()).isBlocked(player.getItemInHand().getType(), ListType.USE)){
type = AlertType.ILLEGAL;
}
}
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){
type = AlertType.LEGAL;
}
// Set messages
message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + player.getItemInHand().getType().name().replace("_", " ");
playerMessage = plugin.getMessage("blocked-action.use-item");
trigger = AlertTrigger.USE_ITEM;
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.USE);
playerMessage = factory.toString();
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
if(hasMobCatcher && player.getItemInHand() != null){
ItemStack item = player.getItemInHand();
if(item.getType() == Material.EGG || item.getType() == Material.MONSTER_EGG){
item.addUnsafeEnchantment(Enchantment.ARROW_KNOCKBACK, 1);
}
}
}
// Alert (with sanity check)
if(type != AlertType.LEGAL){
plugin.getAlerts().alert(message, player, playerMessage, type, trigger);
}
}
// ################# Player Interact Entity
@EventHandler (priority = EventPriority.LOWEST)
public void onInteractEntity(PlayerInteractEntityEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
AlertType type = AlertType.ILLEGAL;
// Convert entity -> item ID
Material item = Material.AIR;
if(event.getRightClicked() instanceof StorageMinecart){
item = Material.STORAGE_MINECART;
}else if(event.getRightClicked() instanceof PoweredMinecart){
item = Material.POWERED_MINECART;
}else if(event.getRightClicked() instanceof Boat){
item = Material.BOAT;
}else if(event.getRightClicked() instanceof Minecart){
item = Material.MINECART;
}else if(event.getRightClicked() instanceof Painting){
item = Material.PAINTING;
}
// If the entity is not found, ignore the event
if(item == Material.AIR){
return;
}
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(event.getRightClicked().getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(item, ListType.RIGHT_CLICK)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(item, ListType.RIGHT_CLICK)){
type = AlertType.LEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to right click " : " right clicked ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(item.name());
String playerMessage = plugin.getMessage("blocked-action.right-click");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.RIGHT_CLICK, ASUtils.capitalize(item.name()));
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.RIGHT_CLICK);
}
// ################# Cart Death Check
@EventHandler (priority = EventPriority.LOWEST)
public void onCartDeath(VehicleDestroyEvent event){
if(event.isCancelled())
return;
Entity attacker = event.getAttacker();
Vehicle potentialCart = event.getVehicle();
// Sanity checks
if(attacker == null || !(potentialCart instanceof StorageMinecart)){
return;
}
if(!(attacker instanceof Player)){
return;
}
// Setup
Player player = (Player) attacker;
StorageMinecart cart = (StorageMinecart) potentialCart;
// Check internal inventories
if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING)){
// Check inventories
ASRegion asregion = plugin.getRegionManager().getRegion(cart.getLocation());
if(asregion != null){
if(asregion.getConfig().clearBlockInventoryOnBreak()){
cart.getInventory().clear();
}
}else{
if(config.get(player.getWorld()).clearBlockInventoryOnBreak()){
cart.getInventory().clear();
}
}
}
}
// ################# Egg Check
@EventHandler (priority = EventPriority.LOWEST)
public void onEggThrow(PlayerEggThrowEvent event){
Player player = event.getPlayer();
AlertType type = AlertType.ILLEGAL;
Material item = Material.EGG;
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(event.getEgg().getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(item, ListType.USE)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(item, ListType.USE)){
type = AlertType.LEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setHatching(false);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(item.name());
String playerMessage = plugin.getMessage("blocked-action.use-item");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.USE, ASUtils.capitalize(item.name()));
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.USE_ITEM);
}
// ################# Experience Bottle Check
@EventHandler (priority = EventPriority.LOWEST)
public void onExpBottle(ExpBottleEvent event){
if(event.getExperience() == 0)
return;
ThrownExpBottle bottle = event.getEntity();
LivingEntity shooter = bottle.getShooter();
AlertType type = AlertType.ILLEGAL;
Material item = Material.EXP_BOTTLE;
// Sanity Check
if(!(shooter instanceof Player)){
return;
}
// Setup
Player player = (Player) shooter;
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(bottle.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(item, ListType.USE)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(item, ListType.USE)){
type = AlertType.LEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setExperience(0);
event.setShowEffect(false);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(item.name());
String playerMessage = plugin.getMessage("blocked-action.use-item");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.USE, ASUtils.capitalize(item.name()));
playerMessage = factory.toString();
if(type == AlertType.ILLEGAL){ // We don't want to show legal events because of spam
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.USE_ITEM);
}
}
// ################# Drop Item
@EventHandler (priority = EventPriority.LOWEST)
public void onDrop(PlayerDropItemEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Item item = event.getItemDrop();
ItemStack itemStack = item.getItemStack();
AlertType type = AlertType.ILLEGAL;
boolean region = false;
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_DROP, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(item.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(itemStack.getType(), ListType.DROP)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(itemStack.getType(), ListType.DROP)){
type = AlertType.LEGAL;
}
}
// Region Check
if(plugin.getRegionManager().getRegion(player.getLocation()) != plugin.getRegionManager().getRegion(item.getLocation()) && type == AlertType.LEGAL){
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_THROW)){
type = AlertType.ILLEGAL;
region = true;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to throw " : " threw ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(itemStack.getType().name());
String playerMessage = plugin.getMessage("blocked-action.drop-item");
if(region){
message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to throw " : " threw ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(itemStack.getType().name()) + ChatColor.WHITE + " into a region.";
playerMessage = ChatColor.RED + "You cannot throw items into another region!";
}
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.ITEM_DROP, ASUtils.capitalize(itemStack.getType().name()));
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.ITEM_DROP);
}
// ################# Pickup Item
@EventHandler (priority = EventPriority.LOWEST)
public void onPickup(PlayerPickupItemEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Item item = event.getItem();
ItemStack itemStack = item.getItemStack();
AlertType type = AlertType.ILLEGAL;
boolean region = false;
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_PICKUP, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(item.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(itemStack.getType(), ListType.PICKUP)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(itemStack.getType(), ListType.PICKUP)){
type = AlertType.LEGAL;
}
}
// Region Check
if(plugin.getRegionManager().getRegion(player.getLocation()) != plugin.getRegionManager().getRegion(item.getLocation()) && type == AlertType.LEGAL){
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_PICKUP)){
type = AlertType.ILLEGAL;
region = true;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to pickup " : " picked up ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(itemStack.getType().name());
String playerMessage = plugin.getMessage("blocked-action.pickup-item");
if(region){
message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to pickup " : " picked up ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(itemStack.getType().name()) + ChatColor.WHITE + " from a region.";
playerMessage = ChatColor.RED + "You cannot pickup items from another region!";
}
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.ITEM_PICKUP, ASUtils.capitalize(itemStack.getType().name()));
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.ITEM_PICKUP);
}
// ################# Player Death
@EventHandler (priority = EventPriority.LOWEST)
public void onDeath(PlayerDeathEvent event){
Player player = event.getEntity();
List<ItemStack> drops = event.getDrops();
AlertType type = AlertType.ILLEGAL;
int illegalItems = 0;
// Remove them from a region (if applicable)
ASRegion region = plugin.getRegionManager().getRegion(player.getLocation());
if(region != null){
region.alertExit(player);
}
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_DEATH, player.getWorld())){
type = AlertType.LEGAL;
}
// Handle event
if(type == AlertType.ILLEGAL){
List<ItemStack> remove = new ArrayList<ItemStack>();
ASRegion asregion = plugin.getRegionManager().getRegion(player.getLocation());
for(ItemStack item : drops){
if(asregion != null){
if(asregion.getConfig().isBlocked(item.getType(), ListType.DEATH)){
illegalItems++;
remove.add(item);
}
}else{
if(config.get(player.getWorld()).isBlocked(item.getType(), ListType.DEATH)){
illegalItems++;
remove.add(item);
}
}
}
// Remove items
for(ItemStack item : remove){
drops.remove(item);
}
}
// Determine new status
if(illegalItems == 0){
type = AlertType.LEGAL;
}
// Alert
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " died with " + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + illegalItems + " illegal item(s).";
String playerMessage = plugin.getMessage("blocked-action.die-with-item");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.DEATH);
factory.insertAmount(illegalItems);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.PLAYER_DEATH);
}
// ################# Player Command
@EventHandler (priority = EventPriority.LOWEST)
public void onCommand(PlayerCommandPreprocessEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
String command = event.getMessage().toLowerCase();
AlertType type = AlertType.ILLEGAL;
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_PICKUP, player.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(player.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(command, ListType.COMMAND)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(player.getWorld()).isBlocked(command, ListType.COMMAND)){
type = AlertType.LEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use the command " : " used the command ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + command;
String playerMessage = plugin.getMessage("blocked-action.command");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.COMMAND);
factory.insertCommand(command);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.COMMAND, !(event.getMessage().toLowerCase().startsWith("/as money")));
}
// ################# Player Move
@EventHandler
public void onMove(PlayerMoveEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
ASRegion currentRegion = plugin.getRegionManager().getRegion(event.getFrom());
ASRegion toRegion = plugin.getRegionManager().getRegion(event.getTo());
// Check split
if(config.get(player.getWorld()).isSplitActive()){
config.get(player.getWorld()).warnSplit(player);
config.get(player.getWorld()).checkSplit(player);
}
if(currentRegion == null){
// Determine alert for World Split
config.get(player.getWorld()).warnSplit(player);
// Check world split
config.get(player.getWorld()).checkSplit(player);
}
// Check regions
if(currentRegion != toRegion){
if(currentRegion != null){
currentRegion.alertExit(player);
}
if(toRegion != null){
toRegion.alertEntry(player);
}
}
}
// ################# Player Game Mode Change
@EventHandler (priority = EventPriority.HIGHEST)
public void onGameModeChange(PlayerGameModeChangeEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
GameMode from = player.getGameMode();
GameMode to = event.getNewGameMode();
boolean ignore = true;
boolean checkRegion = true;
// Check to see if we should even bother
if(!plugin.getConfig().getBoolean("handled-actions.gamemode-inventories")){
return;
}
// Tag check
if(player.hasMetadata("antishare-regionleave")){
player.removeMetadata("antishare-regionleave", plugin);
checkRegion = false;
}
// Region Check
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_ROAM) && checkRegion){
ASRegion region = plugin.getRegionManager().getRegion(player.getLocation());
if(region != null){
ASUtils.sendToPlayer(player, ChatColor.RED + "You are in a region and therefore cannot change Game Mode");
event.setCancelled(true);
return;
}
}
// Check temp
if(plugin.getInventoryManager().isInTemporary(player)){
plugin.getInventoryManager().removeFromTemporary(player);
}
if(!plugin.getPermissions().has(player, PermissionNodes.NO_SWAP)){
// Save from
switch (from){
case CREATIVE:
plugin.getInventoryManager().saveCreativeInventory(player, player.getWorld());
break;
case SURVIVAL:
plugin.getInventoryManager().saveSurvivalInventory(player, player.getWorld());
break;
}
// Set to
switch (to){
case CREATIVE:
plugin.getInventoryManager().getCreativeInventory(player, player.getWorld()).setTo(player);
break;
case SURVIVAL:
plugin.getInventoryManager().getSurvivalInventory(player, player.getWorld()).setTo(player);
break;
}
// Check for open inventories and stuff
Material inventory = Material.AIR;
InventoryView view = player.getOpenInventory();
switch (view.getType()){
case CHEST:
inventory = Material.CHEST;
break;
case DISPENSER:
inventory = Material.DISPENSER;
break;
case FURNACE:
inventory = Material.FURNACE;
break;
case WORKBENCH:
inventory = Material.WORKBENCH;
break;
case ENCHANTING:
inventory = Material.ENCHANTMENT_TABLE;
break;
case BREWING:
inventory = Material.BREWING_STAND;
break;
}
if(inventory != Material.AIR){
AlertType type = AlertType.LEGAL;
ASRegion asregion = plugin.getRegionManager().getRegion(player.getLocation());
if(asregion != null){
if(asregion.getConfig().isBlocked(inventory, ListType.RIGHT_CLICK)){
type = AlertType.ILLEGAL;
}
}else{
if(config.get(player.getWorld()).isBlocked(inventory, ListType.RIGHT_CLICK)){
type = AlertType.ILLEGAL;
}
}
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, player.getWorld(), true)){
type = AlertType.LEGAL;
}
if(asregion != null){
if(asregion.getConfig().isBlocked(inventory, ListType.USE)){
type = AlertType.ILLEGAL;
}
}else{
if(config.get(player.getWorld()).isBlocked(inventory, ListType.USE)){
type = AlertType.ILLEGAL;
}
}
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld(), true)){
type = AlertType.LEGAL;
}
if(type == AlertType.ILLEGAL){
player.closeInventory();
}
}
// For alerts
ignore = false;
}
// Alerts
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " changed to Game Mode " + ChatColor.YELLOW + to.name();
String playerMessage = ignore ? "no message" : "Your inventory has been changed to " + ChatColor.YELLOW + to.name();
if(!plugin.getConfig().getBoolean("other.send-gamemode-change-message")){
playerMessage = "no message";
}
plugin.getAlerts().alert(message, player, playerMessage, AlertType.GENERAL, AlertTrigger.GENERAL);
}
// ################# Player Combat
@EventHandler (priority = EventPriority.LOWEST)
public void onCombat(EntityDamageByEntityEvent event){
if(event.isCancelled())
return;
DamageCause cause = event.getCause();
Entity attacker = event.getDamager();
Entity target = event.getEntity();
AlertType type = AlertType.ILLEGAL;
boolean playerCombat = false;
Player playerAttacker = null;
// Check case
switch (cause){
case ENTITY_ATTACK:
// attacker = entity
if(attacker instanceof Player){
playerAttacker = (Player) attacker;
}else{
return;
}
break;
case PROJECTILE:
// attacker = Projectile
Projectile projectile = (Projectile) attacker;
LivingEntity shooter = projectile.getShooter();
if(shooter instanceof Player){
playerAttacker = (Player) shooter;
}else{
return;
}
break;
default:
return;
}
// Determine if we are hitting a mob or not, and whether it is legal
if(target instanceof Player){
// target = Player
playerCombat = true;
if(!plugin.isBlocked(playerAttacker, PermissionNodes.ALLOW_COMBAT_PLAYERS, playerAttacker.getWorld())){
type = AlertType.LEGAL;
}
}else{
// target = other entity
if(!plugin.isBlocked(playerAttacker, PermissionNodes.ALLOW_COMBAT_MOBS, playerAttacker.getWorld())){
type = AlertType.LEGAL;
}
}
// Check if we need to continue based on settings
ASRegion asregion = plugin.getRegionManager().getRegion(target.getLocation());
if(playerCombat){
if(asregion != null){
if(!asregion.getConfig().combatAgainstPlayers()){
return;
}
}else{
if(!config.get(target.getWorld()).combatAgainstPlayers()){
return;
}
}
}else{
if(asregion != null){
if(!asregion.getConfig().combatAgainstMobs()){
return;
}
}else{
if(!config.get(target.getWorld()).combatAgainstMobs()){
return;
}
}
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
// Alert
String message = "no message";
String playerMessage = "no message";
AlertTrigger trigger = AlertTrigger.HIT_MOB;
TenderType tender = TenderType.HIT_MOB;
String targetFactoryName;
if(playerCombat){
String playerName = ((Player) target).getName();
message = ChatColor.YELLOW + playerAttacker.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to hit " + ChatColor.RED : " hit " + ChatColor.GREEN) + playerName;
playerMessage = plugin.getMessage("blocked-action.hit-player");
trigger = AlertTrigger.HIT_PLAYER;
tender = TenderType.HIT_PLAYER;
targetFactoryName = playerName;
}else{
String targetName = target.getClass().getName().replace("Craft", "").replace("org.bukkit.craftbukkit.entity.", "").trim();
message = ChatColor.YELLOW + playerAttacker.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to hit a " + ChatColor.RED : " hit a " + ChatColor.GREEN) + targetName;
playerMessage = plugin.getMessage("blocked-action.hit-mob");
targetFactoryName = targetName;
}
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, playerAttacker, playerAttacker.getWorld(), tender);
if(tender == TenderType.HIT_MOB){
factory.insertHitMob(targetFactoryName);
}else{
factory.insertHitPlayer(targetFactoryName);
}
playerMessage = factory.toString();
plugin.getAlerts().alert(message, playerAttacker, playerMessage, type, trigger);
}
// ################# Entity Target
@EventHandler (priority = EventPriority.LOWEST)
public void onEntityTarget(EntityTargetEvent event){
if(event.isCancelled())
return;
Entity target = event.getTarget();
Player playerTarget = null;
AlertType type = AlertType.ILLEGAL;
// Check target
if(target instanceof Player){
playerTarget = (Player) target;
}else{
return;
}
// Check permissions
if(!plugin.isBlocked(playerTarget, PermissionNodes.ALLOW_COMBAT_MOBS, playerTarget.getWorld())){
type = AlertType.LEGAL;
}
// Handle event
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
}
}
// ################# Piston Move (Extend)
@EventHandler (priority = EventPriority.LOWEST)
public void onPistonExtend(BlockPistonExtendEvent event){
if(event.isCancelled())
return;
for(Block block : event.getBlocks()){
// Check for block type
GameMode type = plugin.getBlockManager().getType(block);
// Sanity
if(type == null){
continue;
}
// Setup
Location oldLocation = block.getLocation();
Location newLocation = block.getRelative(event.getDirection()).getLocation();
// Move
plugin.getBlockManager().moveBlock(oldLocation, newLocation);
}
}
// ################# Piston Move (Retract)
@EventHandler (priority = EventPriority.LOWEST)
public void onPistonRetract(BlockPistonRetractEvent event){
if(event.isCancelled())
return;
if(!event.isSticky()){ // Only handle moving blocks
return;
}
Block block = event.getBlock().getRelative(event.getDirection()).getRelative(event.getDirection());
// Check for block type
GameMode type = plugin.getBlockManager().getType(block);
// Sanity
if(type == null){
return;
}
// Setup
Location oldLocation = block.getLocation();
Location newLocation = block.getRelative(event.getDirection().getOppositeFace()).getLocation();
// Move
plugin.getBlockManager().moveBlock(oldLocation, newLocation);
}
// ################# Player Join
@EventHandler
public void onJoin(PlayerJoinEvent event){
Player player = event.getPlayer();
// Tell the inventory manager to prepare this player
plugin.getInventoryManager().loadPlayer(player);
// Check region
ASRegion region = plugin.getRegionManager().getRegion(player.getLocation());
if(region != null){
// Add join key
player.setMetadata("antishare-regionleave", new FixedMetadataValue(plugin, true));
// Alert entry
region.alertSilentEntry(player); // Sets inventory and Game Mode
// This must be done because when the inventory manager releases
// a player it resets the inventory to "non-temp"
}
// Money (fines/rewards) status
plugin.getMoneyManager().showStatusOnLogin(player);
}
// ################# Player Quit
@EventHandler
public void onQuit(PlayerQuitEvent event){
Player player = event.getPlayer();
// Remove from regions
ASRegion region = plugin.getRegionManager().getRegion(player.getLocation());
if(region != null){
region.alertExit(player);
}
// Tell the inventory manager to release this player
plugin.getInventoryManager().releasePlayer(player);
}
// ################# Player Kicked
@EventHandler
public void onKick(PlayerKickEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
// Remove from regions
ASRegion region = plugin.getRegionManager().getRegion(player.getLocation());
if(region != null){
region.alertExit(player);
}
// Tell the inventory manager to release this player
plugin.getInventoryManager().releasePlayer(player);
}
// ################# Player World Change
@EventHandler (priority = EventPriority.LOWEST)
public void onWorldChange(PlayerChangedWorldEvent event){
Player player = event.getPlayer();
World to = player.getWorld();
World from = event.getFrom();
boolean ignore = true;
// Check to see if we should even bother checking
if(!plugin.getConfig().getBoolean("handled-actions.world-transfers")){
// Fix up inventories
plugin.getInventoryManager().fixInventory(player, event.getFrom());
return;
}
// Check temp
if(plugin.getInventoryManager().isInTemporary(player)){
plugin.getInventoryManager().removeFromTemporary(player);
}
// Inventory check
if(!plugin.getPermissions().has(player, PermissionNodes.NO_SWAP)){
// Save from
switch (player.getGameMode()){
case CREATIVE:
plugin.getInventoryManager().saveCreativeInventory(player, from);
break;
case SURVIVAL:
plugin.getInventoryManager().saveSurvivalInventory(player, from);
break;
}
// Set to
switch (player.getGameMode()){
case CREATIVE:
plugin.getInventoryManager().getCreativeInventory(player, to).setTo(player);
break;
case SURVIVAL:
plugin.getInventoryManager().getSurvivalInventory(player, to).setTo(player);
break;
}
// For alerts
ignore = false;
}
// Alerts
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + " changed to world " + ChatColor.YELLOW + to.getName();
String playerMessage = ignore ? "no message" : "Your inventory has been changed to " + ChatColor.YELLOW + to.getName();
plugin.getAlerts().alert(message, player, playerMessage, AlertType.GENERAL, AlertTrigger.GENERAL);
}
// ################# Player Teleport
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerTeleport(PlayerTeleportEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
ASRegion currentRegion = plugin.getRegionManager().getRegion(event.getFrom());
ASRegion toRegion = plugin.getRegionManager().getRegion(event.getTo());
AlertType type = AlertType.ILLEGAL;
// Check teleport cause for ender pearl
Material pearl = Material.ENDER_PEARL;
if(event.getCause() == TeleportCause.ENDER_PEARL){
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_USE, player.getWorld())
|| !plugin.isBlocked(player, PermissionNodes.ALLOW_RIGHT_CLICK, player.getWorld())){
type = AlertType.LEGAL;
}
if(!config.get(player.getWorld()).isBlocked(pearl, ListType.USE)){
type = AlertType.LEGAL;
}
if(!config.get(player.getWorld()).isBlocked(pearl, ListType.RIGHT_CLICK)){
type = AlertType.LEGAL;
}
}else{
type = AlertType.LEGAL;
}
// Check type
if(type == AlertType.ILLEGAL){
event.setCancelled(true);
// Alert (with sanity check)
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to use " : " used ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + ASUtils.capitalize(pearl.name());
String playerMessage = plugin.getMessage("blocked-action.use-item");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(null, player, player.getWorld(), TenderType.USE, ASUtils.capitalize(pearl.name()));
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.USE_ITEM);
// Kill off before region check
return;
}
if(currentRegion == null){
// Determine alert for World Split
config.get(player.getWorld()).warnSplit(player);
// Check world split
config.get(player.getWorld()).checkSplit(player);
}
// Check regions
if(currentRegion != toRegion){
if(currentRegion != null){
currentRegion.alertExit(player);
}
if(toRegion != null){
toRegion.alertEntry(player);
}
}
}
}
| false | true | public void onBlockBreak(BlockBreakEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Block block = event.getBlock();
AlertType type = AlertType.ILLEGAL;
boolean special = false;
boolean region = false;
Boolean drops = null;
AlertType specialType = AlertType.LEGAL;
String blockGM = "Unknown";
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(block.getWorld()).isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}
// Check creative/survival blocks
if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){
GameMode blockGamemode = plugin.getBlockManager().getType(block);
if(blockGamemode != null){
blockGM = blockGamemode.name().toLowerCase();
String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative";
if(player.getGameMode() != blockGamemode){
special = true;
boolean deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny");
drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops");
if(deny){
specialType = AlertType.ILLEGAL;
}
}
}
}
// Check regions
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){
ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation());
ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation());
if(playerRegion != blockRegion){
special = true;
region = true;
specialType = AlertType.ILLEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){
event.setCancelled(true);
}else{
plugin.getBlockManager().removeBlock(block);
}
// Alert
if(special){
if(region){
if(specialType == AlertType.ILLEGAL){
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region.";
String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region";
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK);
}
}else{
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break");
MessageFactory factory = new MessageFactory(specialPlayerMessage);
factory.insert(block, player, block.getWorld(), blockGM.equalsIgnoreCase("creative") ? TenderType.CREATIVE_BLOCK : TenderType.SURVIVAL_BLOCK);
specialPlayerMessage = factory.toString();
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK));
}
}else{
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String playerMessage = plugin.getMessage("blocked-action.break-block");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.BLOCK_BREAK);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK);
}
// Handle drops
if(drops != null){
if(drops){
if(event.isCancelled()){
plugin.getBlockManager().removeBlock(block);
block.breakNaturally();
}
}
}
// Check for 'attached' blocks and internal inventories
if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING) && !event.isCancelled()){
// Check inventories
if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){
if(block.getState() instanceof Chest){
Chest state = (Chest) block.getState();
state.getBlockInventory().clear();
}else if(block.getState() instanceof Jukebox){
Jukebox state = (Jukebox) block.getState();
state.setPlaying(null);
}else if(block.getState() instanceof Furnace){
Furnace state = (Furnace) block.getState();
state.getInventory().clear();
}else if(block.getState() instanceof BrewingStand){
BrewingStand state = (BrewingStand) block.getState();
state.getInventory().clear();
}
}
// Check for attached blocks
if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){
for(BlockFace face : BlockFace.values()){
Block rel = block.getRelative(face);
if(ASUtils.isDroppedOnBreak(rel, block)){
plugin.getBlockManager().removeBlock(rel);
rel.setType(Material.AIR);
}
}
}
}
}
| public void onBlockBreak(BlockBreakEvent event){
if(event.isCancelled())
return;
Player player = event.getPlayer();
Block block = event.getBlock();
AlertType type = AlertType.ILLEGAL;
boolean special = false;
boolean region = false;
Boolean drops = null;
boolean deny = false;
AlertType specialType = AlertType.LEGAL;
String blockGM = "Unknown";
// Check if they should be blocked
if(!plugin.isBlocked(player, PermissionNodes.ALLOW_BLOCK_BREAK, block.getWorld())){
type = AlertType.LEGAL;
}
ASRegion asregion = plugin.getRegionManager().getRegion(block.getLocation());
if(asregion != null){
if(!asregion.getConfig().isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}else{
if(!config.get(block.getWorld()).isBlocked(block, ListType.BLOCK_BREAK)){
type = AlertType.LEGAL;
}
}
// Check creative/survival blocks
if(!plugin.getPermissions().has(player, PermissionNodes.FREE_PLACE)){
GameMode blockGamemode = plugin.getBlockManager().getType(block);
if(blockGamemode != null){
blockGM = blockGamemode.name().toLowerCase();
String oGM = blockGM.equalsIgnoreCase("creative") ? "survival" : "creative";
if(player.getGameMode() != blockGamemode){
special = true;
deny = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.deny");
drops = plugin.getConfig().getBoolean("settings." + oGM + "-breaking-" + blockGM + "-blocks.block-drops");
if(deny){
specialType = AlertType.ILLEGAL;
}
}
}
}
// Check regions
if(!plugin.getPermissions().has(player, PermissionNodes.REGION_BREAK)){
ASRegion playerRegion = plugin.getRegionManager().getRegion(player.getLocation());
ASRegion blockRegion = plugin.getRegionManager().getRegion(block.getLocation());
if(playerRegion != blockRegion){
special = true;
region = true;
specialType = AlertType.ILLEGAL;
}
}
// Handle event
if(type == AlertType.ILLEGAL || specialType == AlertType.ILLEGAL){
event.setCancelled(true);
}else{
plugin.getBlockManager().removeBlock(block);
}
// Alert
if(special){
if(region){
if(specialType == AlertType.ILLEGAL){
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break " : " broke ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ") + ChatColor.WHITE + " in a region.";
String specialPlayerMessage = ChatColor.RED + "You cannot break blocks that are not in your region";
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, AlertTrigger.BLOCK_BREAK);
}
}else{
String specialMessage = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (specialType == AlertType.ILLEGAL ? " tried to break the " + blockGM + " block " : " broke the " + blockGM + " block ") + (specialType == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String specialPlayerMessage = plugin.getMessage("blocked-action." + blockGM + "-block-break");
MessageFactory factory = new MessageFactory(specialPlayerMessage);
factory.insert(block, player, block.getWorld(), blockGM.equalsIgnoreCase("creative") ? TenderType.CREATIVE_BLOCK : TenderType.SURVIVAL_BLOCK);
specialPlayerMessage = factory.toString();
plugin.getAlerts().alert(specialMessage, player, specialPlayerMessage, specialType, (blockGM.equalsIgnoreCase("creative") ? AlertTrigger.CREATIVE_BLOCK : AlertTrigger.SURVIVAL_BLOCK));
}
}else{
String message = ChatColor.YELLOW + player.getName() + ChatColor.WHITE + (type == AlertType.ILLEGAL ? " tried to break " : " broke ") + (type == AlertType.ILLEGAL ? ChatColor.RED : ChatColor.GREEN) + block.getType().name().replace("_", " ");
String playerMessage = plugin.getMessage("blocked-action.break-block");
MessageFactory factory = new MessageFactory(playerMessage);
factory.insert(block, player, block.getWorld(), TenderType.BLOCK_BREAK);
playerMessage = factory.toString();
plugin.getAlerts().alert(message, player, playerMessage, type, AlertTrigger.BLOCK_BREAK);
}
// Handle drops
if(drops != null && !deny && special){
if(drops){
plugin.getBlockManager().removeBlock(block);
block.breakNaturally();
}else{
plugin.getBlockManager().removeBlock(block);
block.setType(Material.AIR);
}
}
// Check for 'attached' blocks and internal inventories
if(player.getGameMode() == GameMode.CREATIVE && !plugin.getPermissions().has(player, PermissionNodes.BREAK_ANYTHING) && !event.isCancelled()){
// Check inventories
if(config.get(block.getWorld()).clearBlockInventoryOnBreak()){
if(block.getState() instanceof Chest){
Chest state = (Chest) block.getState();
state.getBlockInventory().clear();
}else if(block.getState() instanceof Jukebox){
Jukebox state = (Jukebox) block.getState();
state.setPlaying(null);
}else if(block.getState() instanceof Furnace){
Furnace state = (Furnace) block.getState();
state.getInventory().clear();
}else if(block.getState() instanceof BrewingStand){
BrewingStand state = (BrewingStand) block.getState();
state.getInventory().clear();
}
}
// Check for attached blocks
if(config.get(block.getWorld()).removeAttachedBlocksOnBreak()){
for(BlockFace face : BlockFace.values()){
Block rel = block.getRelative(face);
if(ASUtils.isDroppedOnBreak(rel, block)){
plugin.getBlockManager().removeBlock(rel);
rel.setType(Material.AIR);
}
}
}
}
}
|
diff --git a/src/com/omartech/tdg/action/seller/SellerAuthAction.java b/src/com/omartech/tdg/action/seller/SellerAuthAction.java
index 40da820..3e21d0e 100644
--- a/src/com/omartech/tdg/action/seller/SellerAuthAction.java
+++ b/src/com/omartech/tdg/action/seller/SellerAuthAction.java
@@ -1,152 +1,154 @@
package com.omartech.tdg.action.seller;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import com.omartech.tdg.mapper.NoticeMapper;
import com.omartech.tdg.model.Notice;
import com.omartech.tdg.model.Seller;
import com.omartech.tdg.service.seller.SellerAuthService;
import com.omartech.tdg.utils.UserType;
@Controller
public class SellerAuthAction {
Logger logger = Logger.getLogger(SellerAuthAction.class);
@Autowired
private SellerAuthService sellerAuthService;
@Autowired
private NoticeMapper noticeMapper;
@RequestMapping(value="/loginasseller")
public String loginAsSeller(HttpSession session){
Seller seller = (Seller) session.getAttribute("seller");
if(seller!=null){
return "redirect:/seller/welcome";
}
return "seller/auth/login";
}
@RequestMapping(value="/seller/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/sellerindex";
}
@RequestMapping(value="/sellerlogin", method=RequestMethod.POST)
public String sellerLogin(@RequestParam(value="email") String email,
@RequestParam(value="password") String password, HttpSession session){
logger.info("seller login:"+email+" - "+password);
Seller seller = sellerAuthService.getSellerByEmailAndPassword(email, password);
if(seller!=null){
session.setAttribute("seller", seller);
return "redirect:/seller/welcome";
}else{
return "redirect:/loginasseller";
}
}
@RequestMapping(value="/seller/welcome")
public ModelAndView welcome(){
Notice notice = noticeMapper.getNoticeByUserType(UserType.SELLER);
return new ModelAndView("seller/auth/welcome").addObject("notice", notice);
}
@RequestMapping(value="/sellerforgetpwd")
public String sellerForgetPwd(){
return "seller/auth/forget";
}
@RequestMapping(value="/registerasseller")
public String registerAsSeller(){
return "seller/auth/register";
}
@RequestMapping(value="/sellerregist", method=RequestMethod.POST)
public String sellerRegister(
@RequestParam(value="email", required=true) String email,
@RequestParam(value="password", required=true) String password,
@RequestParam String businessName,
@RequestParam String firstName,
@RequestParam String lastName,
@RequestParam String businessAddress,
@RequestParam String city,
+ @RequestParam String state,
@RequestParam String country,
@RequestParam String primaryPhoneNumber,
@RequestParam String productLines,
@RequestParam String secondPhoneNumber,
@RequestParam String companyWebsiteAddress,
HttpSession session){
Seller checkSeller = sellerAuthService.getSellerByEmail(email);
if(checkSeller == null){
Seller seller = new Seller();
seller.setEmail(email);
seller.setPassword(password);
seller.setBusinessName(businessName);
seller.setFirstName(firstName);
seller.setLastName(lastName);
seller.setBusinessAddress(businessAddress);
seller.setCity(city);
+ seller.setState(state);
seller.setCountry(country);
seller.setPrimaryPhoneNumber(primaryPhoneNumber);
seller.setProductLines(productLines);
seller.setSecondPhoneNumber(secondPhoneNumber);
seller.setCompanyWebsiteAddress(companyWebsiteAddress);
sellerAuthService.insertSeller(seller);
session.setAttribute("seller", seller);
return "redirect:/seller/welcome";
}else{
return "redirect:/sellerindex";
}
}
@RequestMapping("/seller/auth/show")
public ModelAndView showProfile(HttpSession session){
Seller se = (Seller)session.getAttribute("seller");
String email = se.getEmail();
Seller seller = sellerAuthService.getSellerByEmail(email);
return new ModelAndView("/seller/auth/show").addObject("selller", seller);
}
@RequestMapping("/seller/auth/edit")
public ModelAndView editProfile(HttpSession session){
Seller se = (Seller)session.getAttribute("seller");
String email = se.getEmail();
Seller seller = sellerAuthService.getSellerByEmail(email);
return new ModelAndView("/seller/auth/modify").addObject("selller", seller);
}
@RequestMapping("/seller/auth/update")
public String editProfile(@RequestParam String email, @RequestParam String password,HttpSession session){
Seller se = (Seller)session.getAttribute("seller");
String em = se.getEmail();
if(em.equals(email)){
se.setPassword(password);
}
sellerAuthService.updateSeller(se);
return "redirect:/seller/auth/show";
}
public SellerAuthService getSellerAuthService() {
return sellerAuthService;
}
public void setSellerAuthService(SellerAuthService sellerAuthService) {
this.sellerAuthService = sellerAuthService;
}
public NoticeMapper getNoticeMapper() {
return noticeMapper;
}
public void setNoticeMapper(NoticeMapper noticeMapper) {
this.noticeMapper = noticeMapper;
}
}
| false | true | public String sellerRegister(
@RequestParam(value="email", required=true) String email,
@RequestParam(value="password", required=true) String password,
@RequestParam String businessName,
@RequestParam String firstName,
@RequestParam String lastName,
@RequestParam String businessAddress,
@RequestParam String city,
@RequestParam String country,
@RequestParam String primaryPhoneNumber,
@RequestParam String productLines,
@RequestParam String secondPhoneNumber,
@RequestParam String companyWebsiteAddress,
HttpSession session){
Seller checkSeller = sellerAuthService.getSellerByEmail(email);
if(checkSeller == null){
Seller seller = new Seller();
seller.setEmail(email);
seller.setPassword(password);
seller.setBusinessName(businessName);
seller.setFirstName(firstName);
seller.setLastName(lastName);
seller.setBusinessAddress(businessAddress);
seller.setCity(city);
seller.setCountry(country);
seller.setPrimaryPhoneNumber(primaryPhoneNumber);
seller.setProductLines(productLines);
seller.setSecondPhoneNumber(secondPhoneNumber);
seller.setCompanyWebsiteAddress(companyWebsiteAddress);
sellerAuthService.insertSeller(seller);
session.setAttribute("seller", seller);
return "redirect:/seller/welcome";
}else{
return "redirect:/sellerindex";
}
}
| public String sellerRegister(
@RequestParam(value="email", required=true) String email,
@RequestParam(value="password", required=true) String password,
@RequestParam String businessName,
@RequestParam String firstName,
@RequestParam String lastName,
@RequestParam String businessAddress,
@RequestParam String city,
@RequestParam String state,
@RequestParam String country,
@RequestParam String primaryPhoneNumber,
@RequestParam String productLines,
@RequestParam String secondPhoneNumber,
@RequestParam String companyWebsiteAddress,
HttpSession session){
Seller checkSeller = sellerAuthService.getSellerByEmail(email);
if(checkSeller == null){
Seller seller = new Seller();
seller.setEmail(email);
seller.setPassword(password);
seller.setBusinessName(businessName);
seller.setFirstName(firstName);
seller.setLastName(lastName);
seller.setBusinessAddress(businessAddress);
seller.setCity(city);
seller.setState(state);
seller.setCountry(country);
seller.setPrimaryPhoneNumber(primaryPhoneNumber);
seller.setProductLines(productLines);
seller.setSecondPhoneNumber(secondPhoneNumber);
seller.setCompanyWebsiteAddress(companyWebsiteAddress);
sellerAuthService.insertSeller(seller);
session.setAttribute("seller", seller);
return "redirect:/seller/welcome";
}else{
return "redirect:/sellerindex";
}
}
|
diff --git a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java
index f40d8935c..fd067f7a8 100755
--- a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java
+++ b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java
@@ -1,1418 +1,1418 @@
/*
* ASTRID: Android's Simple Task Recording Dashboard
*
* Copyright (c) 2009 Tim Su
*
* 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.todoroo.astrid.activity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemSelectedListener;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.alarms.AlarmControlSet;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.gcal.GCalControlSet;
import com.todoroo.astrid.producteev.ProducteevControlSet;
import com.todoroo.astrid.producteev.ProducteevUtilities;
import com.todoroo.astrid.reminders.Notifications;
import com.todoroo.astrid.repeats.RepeatControlSet;
import com.todoroo.astrid.service.AddOnService;
import com.todoroo.astrid.service.MetadataService;
import com.todoroo.astrid.service.StartupService;
import com.todoroo.astrid.service.StatisticsService;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.tags.TagsControlSet;
import com.todoroo.astrid.timers.TimerControlSet;
import com.todoroo.astrid.ui.CalendarDialog;
import com.todoroo.astrid.ui.DeadlineTimePickerDialog;
import com.todoroo.astrid.ui.DeadlineTimePickerDialog.OnDeadlineTimeSetListener;
import com.todoroo.astrid.voice.VoiceInputAssistant;
/**
* This activity is responsible for creating new tasks and editing existing
* ones. It saves a task when it is paused (screen rotated, back button
* pressed) as long as the task has a title.
*
* @author timsu
*
*/
public final class TaskEditActivity extends TabActivity {
// --- bundle tokens
/**
* Task ID
*/
public static final String TOKEN_ID = "id"; //$NON-NLS-1$
/**
* Content Values to set
*/
public static final String TOKEN_VALUES = "v"; //$NON-NLS-1$
/**
* Task in progress (during orientation change)
*/
private static final String TASK_IN_PROGRESS = "task_in_progress"; //$NON-NLS-1$
// --- request codes
@SuppressWarnings("unused")
private static final int REQUEST_CODE_OPERATION = 0;
// --- menu codes
private static final int MENU_SAVE_ID = Menu.FIRST;
private static final int MENU_DISCARD_ID = Menu.FIRST + 1;
private static final int MENU_DELETE_ID = Menu.FIRST + 2;
// --- result codes
public static final int RESULT_CODE_SAVED = RESULT_FIRST_USER;
public static final int RESULT_CODE_DISCARDED = RESULT_FIRST_USER + 1;
public static final int RESULT_CODE_DELETED = RESULT_FIRST_USER + 2;
// --- services
@Autowired
private ExceptionService exceptionService;
@Autowired
private Database database;
@Autowired
private TaskService taskService;
@Autowired
private MetadataService metadataService;
@Autowired
private AddOnService addOnService;
// --- UI components
private ImageButton voiceAddNoteButton;
private EditTextControlSet notesControlSet = null;
private EditText title;
private final List<TaskEditControlSet> controls =
Collections.synchronizedList(new ArrayList<TaskEditControlSet>());
// --- other instance variables
/** true if editing started with a new task */
boolean isNewTask = false;
/** task model */
private Task model = null;
/** whether task should be saved when this activity exits */
private boolean shouldSaveState = true;
/** edit control receiver */
private final ControlReceiver controlReceiver = new ControlReceiver();
/** voice assistant for notes-creation */
private VoiceInputAssistant voiceNoteAssistant = null;
private EditText notesEditText;
private boolean cancelled = false;
/* ======================================================================
* ======================================================= initialization
* ====================================================================== */
public TaskEditActivity() {
DependencyInjectionService.getInstance().inject(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new StartupService().onStartupApplication(this);
setUpUIComponents();
// disable keyboard until user requests it
AndroidUtilities.suppressVirtualKeyboard(title);
// if we were editing a task already, restore it
if(savedInstanceState != null && savedInstanceState.containsKey(TASK_IN_PROGRESS)) {
Task task = savedInstanceState.getParcelable(TASK_IN_PROGRESS);
if(task != null) {
model = task;
}
}
setResult(RESULT_OK);
}
/* ======================================================================
* ==================================================== UI initialization
* ====================================================================== */
/** Initialize UI components */
private void setUpUIComponents() {
Resources r = getResources();
// set up tab host
TabHost tabHost = getTabHost();
tabHost.setPadding(0, 4, 0, 0);
LayoutInflater.from(this).inflate(R.layout.task_edit_activity,
tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_basic)).
setIndicator(r.getString(R.string.TEA_tab_basic),
r.getDrawable(R.drawable.tab_edit)).setContent(
R.id.tab_basic));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_extra)).
setIndicator(r.getString(R.string.TEA_tab_extra),
r.getDrawable(R.drawable.tab_advanced)).setContent(
R.id.tab_extra));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_addons)).
setIndicator(r.getString(R.string.TEA_tab_addons),
r.getDrawable(R.drawable.tab_addons)).setContent(
R.id.tab_addons));
getTabWidget().setBackgroundColor(Color.BLACK);
// populate control set
title = (EditText) findViewById(R.id.title);
controls.add(new EditTextControlSet(Task.TITLE, R.id.title));
controls.add(new ImportanceControlSet(R.id.importance_container));
controls.add(new UrgencyControlSet(R.id.urgency));
+ notesEditText = (EditText) findViewById(R.id.notes);
// prepare and set listener for voice-button
if(addOnService.hasPowerPack()) {
voiceAddNoteButton = (ImageButton) findViewById(R.id.voiceAddNoteButton);
voiceAddNoteButton.setVisibility(View.VISIBLE);
- notesEditText = (EditText) findViewById(R.id.notes);
int prompt = R.string.voice_edit_note_prompt;
voiceNoteAssistant = new VoiceInputAssistant(this, voiceAddNoteButton,
notesEditText);
voiceNoteAssistant.setAppend(true);
voiceNoteAssistant.setLanguageModel(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voiceNoteAssistant.configureMicrophoneButton(prompt);
}
new Thread() {
@Override
public void run() {
AndroidUtilities.sleepDeep(500L);
runOnUiThread(new Runnable() {
public void run() {
// internal add-ins
controls.add(new TagsControlSet(TaskEditActivity.this, R.id.tags_container));
LinearLayout extrasAddons = (LinearLayout) findViewById(R.id.tab_extra_addons);
controls.add(new RepeatControlSet(TaskEditActivity.this, extrasAddons));
controls.add(new GCalControlSet(TaskEditActivity.this, extrasAddons));
LinearLayout addonsAddons = (LinearLayout) findViewById(R.id.tab_addons_addons);
try {
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
controls.add(new ProducteevControlSet(TaskEditActivity.this, addonsAddons));
notesEditText.setHint(R.string.producteev_TEA_notes);
((TextView)findViewById(R.id.notes_label)).setHint(R.string.producteev_TEA_notes);
}
} catch (Exception e) {
Log.e("astrid-error", "loading-control-set", e); //$NON-NLS-1$ //$NON-NLS-2$
}
controls.add(new TimerControlSet(TaskEditActivity.this, addonsAddons));
controls.add(new AlarmControlSet(TaskEditActivity.this, addonsAddons));
if(!addOnService.hasPowerPack()) {
// show add-on help if necessary
View addonsEmpty = findViewById(R.id.addons_empty);
addonsEmpty.setVisibility(View.VISIBLE);
addonsAddons.removeView(addonsEmpty);
addonsAddons.addView(addonsEmpty);
((Button)findViewById(R.id.addons_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addOnActivity = new Intent(TaskEditActivity.this, AddOnActivity.class);
addOnActivity.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true);
startActivity(addOnActivity);
}
});
}
controls.add( new ReminderControlSet(R.id.reminder_due,
R.id.reminder_overdue, R.id.reminder_alarm));
controls.add(new RandomReminderControlSet(R.id.reminder_random,
R.id.reminder_random_interval));
controls.add(new HideUntilControlSet(R.id.hideUntil));
// re-read all
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
});
notesControlSet = new EditTextControlSet(Task.NOTES, R.id.notes);
controls.add(notesControlSet);
// set up listeners
setUpListeners();
}
}.start();
}
/** Set up button listeners */
private void setUpListeners() {
final View.OnClickListener mSaveListener = new View.OnClickListener() {
public void onClick(View v) {
saveButtonClick();
}
};
final View.OnClickListener mDiscardListener = new View.OnClickListener() {
public void onClick(View v) {
discardButtonClick();
}
};
// set up save, cancel, and delete buttons
ImageButton saveButtonGeneral = (ImageButton) findViewById(R.id.save_basic);
saveButtonGeneral.setOnClickListener(mSaveListener);
ImageButton saveButtonDates = (ImageButton) findViewById(R.id.save_extra);
saveButtonDates.setOnClickListener(mSaveListener);
ImageButton saveButtonNotify = (ImageButton) findViewById(R.id.save_addons);
saveButtonNotify.setOnClickListener(mSaveListener);
ImageButton discardButtonGeneral = (ImageButton) findViewById(R.id.discard_basic);
discardButtonGeneral.setOnClickListener(mDiscardListener);
ImageButton discardButtonDates = (ImageButton) findViewById(R.id.discard_extra);
discardButtonDates.setOnClickListener(mDiscardListener);
ImageButton discardButtonNotify = (ImageButton) findViewById(R.id.discard_addons);
discardButtonNotify.setOnClickListener(mDiscardListener);
}
/* ======================================================================
* =============================================== model reading / saving
* ====================================================================== */
/**
* Loads action item from the given intent
* @param intent
*/
@SuppressWarnings("nls")
protected void loadItem(Intent intent) {
if(model != null) {
// came from bundle
isNewTask = (model.getValue(Task.TITLE).length() == 0);
return;
}
long idParam = intent.getLongExtra(TOKEN_ID, -1L);
database.openForReading();
if(idParam > -1L) {
model = taskService.fetchById(idParam, Task.PROPERTIES);
}
// not found by id or was never passed an id
if(model == null) {
String valuesAsString = intent.getStringExtra(TOKEN_VALUES);
ContentValues values = null;
try {
if(valuesAsString != null)
values = AndroidUtilities.contentValuesFromSerializedString(valuesAsString);
} catch (Exception e) {
// oops, can't serialize
}
model = TaskListActivity.createWithValues(values, null, taskService, metadataService);
}
if(model.getValue(Task.TITLE).length() == 0) {
StatisticsService.reportEvent("create-task");
isNewTask = true;
// set deletion date until task gets a title
model.setValue(Task.DELETION_DATE, DateUtilities.now());
} else {
StatisticsService.reportEvent("edit-task");
}
if(model == null) {
exceptionService.reportError("task-edit-no-task",
new NullPointerException("model"));
finish();
return;
}
// clear notification
Notifications.cancelNotifications(model.getId());
}
/** Populate UI component values from the model */
private void populateFields() {
Resources r = getResources();
loadItem(getIntent());
if(isNewTask)
setTitle(R.string.TEA_view_titleNew);
else
setTitle(r.getString(R.string.TEA_view_title, model.getValue(Task.TITLE)));
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
/** Save task model from values in UI components */
private void save() {
StringBuilder toast = new StringBuilder();
for(TaskEditControlSet controlSet : controls) {
String toastText = controlSet.writeToModel(model);
if(toastText != null)
toast.append('\n').append(toastText);
}
if(title.getText().length() > 0)
model.setValue(Task.DELETION_DATE, 0L);
if(taskService.save(model) && title.getText().length() > 0)
showSaveToast(toast.toString());
}
@Override
public void finish() {
super.finish();
// abandon editing and delete the newly created task if
// no title was entered
if(title.getText().length() == 0 && isNewTask && model.isSaved()) {
taskService.delete(model);
}
}
/* ======================================================================
* ================================================ edit control handling
* ====================================================================== */
/**
* Receiver which receives intents to add items to the filter list
*
* @author Tim Su <[email protected]>
*
*/
protected class ControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle extras = intent.getExtras();
RemoteViews view = extras.getParcelable(AstridApiConstants.EXTRAS_RESPONSE);
// add a separator
View separator = new View(TaskEditActivity.this);
separator.setPadding(5, 5, 5, 5);
separator.setBackgroundResource(android.R.drawable.divider_horizontal_dark);
LinearLayout dest = (LinearLayout)findViewById(R.id.tab_addons_addons);
dest.addView(separator);
view.apply(TaskEditActivity.this, dest);
} catch (Exception e) {
exceptionService.reportError("receive-detail-" + //$NON-NLS-1$
intent.getStringExtra(AstridApiConstants.EXTRAS_ADDON), e);
}
}
}
/* ======================================================================
* ======================================================= event handlers
* ====================================================================== */
protected void saveButtonClick() {
setResult(RESULT_OK);
finish();
}
/**
* Displays a Toast reporting that the selected task has been saved and, if
* it has a due date, that is due in 'x' amount of time, to 1 time-unit of
* precision
* @param additionalMessage
*/
private void showSaveToast(String additionalMessage) {
int stringResource;
long due = model.getValue(Task.DUE_DATE);
String toastMessage;
if (due != 0) {
stringResource = R.string.TEA_onTaskSave_due;
CharSequence formattedDate =
DateUtils.getRelativeTimeSpanString(due);
toastMessage = getString(stringResource, formattedDate);
} else {
toastMessage = getString(R.string.TEA_onTaskSave_notDue);
}
int length = additionalMessage.length() == 0 ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
Toast.makeText(this,
toastMessage + additionalMessage,
length).show();
}
protected void discardButtonClick() {
shouldSaveState = false;
// abandon editing in this case
if(title.getText().length() == 0) {
if(isNewTask)
taskService.delete(model);
}
showCancelToast();
setResult(RESULT_CANCELED);
finish();
}
/**
* Show toast for task edit canceling
*/
private void showCancelToast() {
Toast.makeText(this, R.string.TEA_onTaskCancel,
Toast.LENGTH_SHORT).show();
}
protected void deleteButtonClick() {
new AlertDialog.Builder(this)
.setTitle(R.string.DLG_confirm_title)
.setMessage(R.string.DLG_delete_this_task_question)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
taskService.delete(model);
shouldSaveState = false;
showDeleteToast();
setResult(RESULT_CANCELED);
finish();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
/**
* Show toast for task edit deleting
*/
private void showDeleteToast() {
Toast.makeText(this, R.string.TEA_onTaskDelete,
Toast.LENGTH_SHORT).show();
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case MENU_SAVE_ID:
saveButtonClick();
return true;
case MENU_DISCARD_ID:
discardButtonClick();
return true;
case MENU_DELETE_ID:
deleteButtonClick();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem item;
item = menu.add(Menu.NONE, MENU_SAVE_ID, 0, R.string.TEA_menu_save);
item.setIcon(android.R.drawable.ic_menu_save);
item = menu.add(Menu.NONE, MENU_DISCARD_ID, 0, R.string.TEA_menu_discard);
item.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
item = menu.add(Menu.NONE, MENU_DELETE_ID, 0, R.string.TEA_menu_delete);
item.setIcon(android.R.drawable.ic_menu_delete);
return true;
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(controlReceiver);
if(shouldSaveState)
save();
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(controlReceiver,
new IntentFilter(AstridApiConstants.BROADCAST_SEND_EDIT_CONTROLS));
populateFields();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle the result of voice recognition, put it into the appropiate textfield
voiceNoteAssistant.handleActivityResult(requestCode, resultCode, data);
// write the voicenote into the model, or it will be deleted by onResume.populateFields
// (due to the activity-change)
notesControlSet.writeToModel(model);
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// stick our task into the outState
outState.putParcelable(TASK_IN_PROGRESS, model);
}
@Override
protected void onRestoreInstanceState(Bundle inState) {
super.onRestoreInstanceState(inState);
}
@Override
protected void onStart() {
super.onStart();
StatisticsService.sessionStart(this);
}
@Override
protected void onStop() {
super.onStop();
StatisticsService.sessionStop(this);
}
/* ======================================================================
* ========================================== UI component helper classes
* ====================================================================== */
// --- interface
/**
* Interface for working with controls that alter task data
*/
public interface TaskEditControlSet {
/**
* Read data from model to update the control set
*/
public void readFromTask(Task task);
/**
* Write data from control set to model
* @return text appended to the toast
*/
public String writeToModel(Task task);
}
// --- EditTextControlSet
/**
* Control set for mapping a Property to an EditText
* @author Tim Su <[email protected]>
*
*/
public class EditTextControlSet implements TaskEditControlSet {
private final EditText editText;
private final StringProperty property;
public EditTextControlSet(StringProperty property, int editText) {
this.property = property;
this.editText = (EditText)findViewById(editText);
}
@Override
public void readFromTask(Task task) {
editText.setText(task.getValue(property));
}
@Override
public String writeToModel(Task task) {
task.setValue(property, editText.getText().toString());
return null;
}
}
// --- ImportanceControlSet
/**
* Control Set for setting task importance
*
* @author Tim Su <[email protected]>
*
*/
public class ImportanceControlSet implements TaskEditControlSet {
private final List<CompoundButton> buttons = new LinkedList<CompoundButton>();
private final int[] colors = Task.getImportanceColors(getResources());
public ImportanceControlSet(int containerId) {
LinearLayout layout = (LinearLayout)findViewById(containerId);
int min = Task.IMPORTANCE_MOST;
int max = Task.IMPORTANCE_LEAST;
int importanceOffset = max;
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
max = 5;
importanceOffset = max - 1;
}
for(int i = min; i <= max; i++) {
final ToggleButton button = new ToggleButton(TaskEditActivity.this);
button.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1));
StringBuilder label = new StringBuilder();
if(ProducteevUtilities.INSTANCE.isLoggedIn())
label.append(5 - i).append("\n\u2605"); //$NON-NLS-1$
else {
for(int j = importanceOffset; j >= i; j--)
label.append('!');
}
button.setTextColor(colors[i]);
button.setTextOff(label);
button.setTextOn(label);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setImportance((Integer)button.getTag());
}
});
button.setTag(i);
buttons.add(button);
layout.addView(button);
}
}
public void setImportance(Integer i) {
for(CompoundButton b : buttons) {
if(b.getTag() == i) {
b.setTextSize(24);
b.setChecked(true);
b.setBackgroundResource(R.drawable.btn_selected);
} else {
b.setTextSize(16);
b.setChecked(false);
b.setBackgroundResource(android.R.drawable.btn_default);
}
}
}
public Integer getImportance() {
for(CompoundButton b : buttons)
if(b.isChecked())
return (Integer) b.getTag();
return null;
}
@Override
public void readFromTask(Task task) {
setImportance(task.getValue(Task.IMPORTANCE));
}
@Override
public String writeToModel(Task task) {
if(getImportance() != null)
task.setValue(Task.IMPORTANCE, getImportance());
return null;
}
}
// --- UrgencyControlSet
private class UrgencyControlSet implements TaskEditControlSet,
OnItemSelectedListener, OnDeadlineTimeSetListener,
OnCancelListener {
private static final int SPECIFIC_DATE = -1;
private static final int EXISTING_TIME_UNSET = -2;
private final Spinner spinner;
private ArrayAdapter<UrgencyValue> urgencyAdapter;
private int previousSetting = Task.URGENCY_NONE;
private long existingDate = EXISTING_TIME_UNSET;
private int existingDateHour = EXISTING_TIME_UNSET;
private int existingDateMinutes = EXISTING_TIME_UNSET;
/**
* Container class for urgencies
*
* @author Tim Su <[email protected]>
*
*/
private class UrgencyValue {
public String label;
public int setting;
public long dueDate;
public UrgencyValue(String label, int setting) {
this.label = label;
this.setting = setting;
dueDate = model.createDueDate(setting, 0);
}
public UrgencyValue(String label, int setting, long dueDate) {
this.label = label;
this.setting = setting;
this.dueDate = dueDate;
}
@Override
public String toString() {
return label;
}
}
public UrgencyControlSet(int urgency) {
this.spinner = (Spinner)findViewById(urgency);
this.spinner.setOnItemSelectedListener(this);
}
/**
* set up urgency adapter and picks the right selected item
* @param dueDate
*/
private void createUrgencyList(long dueDate) {
// set up base urgency list
String[] labels = getResources().getStringArray(R.array.TEA_urgency);
UrgencyValue[] urgencyValues = new UrgencyValue[labels.length];
urgencyValues[0] = new UrgencyValue(labels[0],
Task.URGENCY_SPECIFIC_DAY_TIME, SPECIFIC_DATE);
urgencyValues[1] = new UrgencyValue(labels[1],
Task.URGENCY_TODAY);
urgencyValues[2] = new UrgencyValue(labels[2],
Task.URGENCY_TOMORROW);
String dayAfterTomorrow = DateUtils.getDayOfWeekString(
new Date(DateUtilities.now() + 2 * DateUtilities.ONE_DAY).getDay() +
Calendar.SUNDAY, DateUtils.LENGTH_LONG);
urgencyValues[3] = new UrgencyValue(dayAfterTomorrow,
Task.URGENCY_DAY_AFTER);
urgencyValues[4] = new UrgencyValue(labels[4],
Task.URGENCY_NEXT_WEEK);
urgencyValues[5] = new UrgencyValue(labels[5],
Task.URGENCY_NONE);
// search for setting
int selection = -1;
for(int i = 0; i < urgencyValues.length; i++)
if(urgencyValues[i].dueDate == dueDate) {
selection = i;
if(dueDate > 0)
existingDate = dueDate;
break;
}
if(selection == -1) {
UrgencyValue[] updated = new UrgencyValue[labels.length + 1];
for(int i = 0; i < labels.length; i++)
updated[i+1] = urgencyValues[i];
if(Task.hasDueTime(dueDate)) {
Date dueDateAsDate = new Date(dueDate);
updated[0] = new UrgencyValue(DateUtilities.getDateStringWithTime(TaskEditActivity.this, dueDateAsDate),
Task.URGENCY_SPECIFIC_DAY_TIME, dueDate);
existingDate = dueDate;
existingDateHour = dueDateAsDate.getHours();
existingDateMinutes = dueDateAsDate.getMinutes();
} else {
updated[0] = new UrgencyValue(DateUtilities.getDateString(TaskEditActivity.this, new Date(dueDate)),
Task.URGENCY_SPECIFIC_DAY, dueDate);
existingDate = dueDate;
existingDateHour = SPECIFIC_DATE;
}
selection = 0;
urgencyValues = updated;
}
urgencyAdapter = new ArrayAdapter<UrgencyValue>(
TaskEditActivity.this, android.R.layout.simple_spinner_item,
urgencyValues);
urgencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.spinner.setAdapter(urgencyAdapter);
this.spinner.setSelection(selection);
}
// --- listening for events
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if specific date or date & time selected, show dialog
// ... at conclusion of dialog, update our list
UrgencyValue item = urgencyAdapter.getItem(position);
if(item.dueDate == SPECIFIC_DATE) {
customSetting = item.setting;
customDate = new Date(existingDate == EXISTING_TIME_UNSET ? DateUtilities.now() : existingDate);
customDate.setSeconds(0);
/***** Calendar Dialog Changes -- Start *****/
final CalendarDialog calendarDialog = new CalendarDialog(TaskEditActivity.this, customDate);
calendarDialog.show();
calendarDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface arg0) {
if (!cancelled) {
setDate(calendarDialog);
}
cancelled = false;
}
});
calendarDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
cancelled = true;
}
});
/***** Calendar Dialog Changes -- End *****/
spinner.setSelection(previousSetting);
} else {
previousSetting = position;
model.setValue(Task.DUE_DATE, item.dueDate);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// ignore
}
Date customDate;
int customSetting;
private void setDate(CalendarDialog calendarDialog) {
customDate = calendarDialog.getCalendarDate();
customDate.setMinutes(0);
if(customSetting != Task.URGENCY_SPECIFIC_DAY_TIME) {
customDateFinished();
return;
}
boolean specificTime = existingDateHour != SPECIFIC_DATE;
if(existingDateHour < 0) {
existingDateHour = customDate.getHours();
existingDateMinutes= customDate.getMinutes();
}
DeadlineTimePickerDialog timePicker = new DeadlineTimePickerDialog(TaskEditActivity.this, this,
existingDateHour, existingDateMinutes,
DateUtilities.is24HourFormat(TaskEditActivity.this),
specificTime);
timePicker.setOnCancelListener(this);
timePicker.show();
}
public void onTimeSet(TimePicker view, boolean hasTime, int hourOfDay, int minute) {
if(!hasTime)
customSetting = Task.URGENCY_SPECIFIC_DAY;
else {
customDate.setHours(hourOfDay);
customDate.setMinutes(minute);
existingDateHour = hourOfDay;
existingDateMinutes = minute;
}
customDateFinished();
}
@Override
public void onCancel(DialogInterface dialog) {
// user canceled, restore previous choice
spinner.setSelection(previousSetting);
}
private void customDateFinished() {
long time = model.createDueDate(customSetting, customDate.getTime());
model.setValue(Task.DUE_DATE, time);
createUrgencyList(time);
}
// --- setting up values
@Override
public void readFromTask(Task task) {
long dueDate = task.getValue(Task.DUE_DATE);
createUrgencyList(dueDate);
}
@Override
public String writeToModel(Task task) {
UrgencyValue item = urgencyAdapter.getItem(spinner.getSelectedItemPosition());
if(item.dueDate != SPECIFIC_DATE) // user canceled specific date
task.setValue(Task.DUE_DATE, item.dueDate);
return null;
}
}
/**
* Control set for specifying when a task should be hidden
*
* @author Tim Su <[email protected]>
*
*/
private class HideUntilControlSet implements TaskEditControlSet,
OnItemSelectedListener, OnCancelListener,
OnDeadlineTimeSetListener {
private static final int SPECIFIC_DATE = -1;
private static final int EXISTING_TIME_UNSET = -2;
private final Spinner spinner;
private int previousSetting = Task.HIDE_UNTIL_NONE;
private long existingDate = EXISTING_TIME_UNSET;
private int existingDateHour = EXISTING_TIME_UNSET;
private int existingDateMinutes = EXISTING_TIME_UNSET;
public HideUntilControlSet(int hideUntil) {
this.spinner = (Spinner) findViewById(hideUntil);
this.spinner.setOnItemSelectedListener(this);
}
private ArrayAdapter<HideUntilValue> adapter;
/**
* Container class for urgencies
*
* @author Tim Su <[email protected]>
*
*/
private class HideUntilValue {
public String label;
public int setting;
public long date;
public HideUntilValue(String label, int setting) {
this(label, setting, 0);
}
public HideUntilValue(String label, int setting, long date) {
this.label = label;
this.setting = setting;
this.date = date;
}
@Override
public String toString() {
return label;
}
}
private HideUntilValue[] createHideUntilList(long specificDate) {
// set up base values
String[] labels = getResources().getStringArray(R.array.TEA_hideUntil);
HideUntilValue[] values = new HideUntilValue[labels.length];
values[0] = new HideUntilValue(labels[0], Task.HIDE_UNTIL_NONE);
values[1] = new HideUntilValue(labels[1], Task.HIDE_UNTIL_DUE);
values[2] = new HideUntilValue(labels[2], Task.HIDE_UNTIL_DAY_BEFORE);
values[3] = new HideUntilValue(labels[3], Task.HIDE_UNTIL_WEEK_BEFORE);
values[4] = new HideUntilValue(labels[4], Task.HIDE_UNTIL_SPECIFIC_DAY, -1);
if(specificDate > 0) {
HideUntilValue[] updated = new HideUntilValue[values.length + 1];
for(int i = 0; i < values.length; i++)
updated[i+1] = values[i];
Date hideUntilAsDate = new Date(specificDate);
if(hideUntilAsDate.getHours() == 0 && hideUntilAsDate.getMinutes() == 0 && hideUntilAsDate.getSeconds() == 0) {
updated[0] = new HideUntilValue(DateUtilities.getDateString(TaskEditActivity.this, new Date(specificDate)),
Task.HIDE_UNTIL_SPECIFIC_DAY, specificDate);
existingDate = specificDate;
existingDateHour = SPECIFIC_DATE;
} else {
updated[0] = new HideUntilValue(DateUtilities.getDateStringWithTime(TaskEditActivity.this, new Date(specificDate)),
Task.HIDE_UNTIL_SPECIFIC_DAY_TIME, specificDate);
existingDate = specificDate;
existingDateHour = hideUntilAsDate.getHours();
existingDateMinutes = hideUntilAsDate.getMinutes();
}
values = updated;
}
return values;
}
// --- listening for events
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if specific date selected, show dialog
// ... at conclusion of dialog, update our list
HideUntilValue item = adapter.getItem(position);
if(item.date == SPECIFIC_DATE) {
customDate = new Date(existingDate == EXISTING_TIME_UNSET ? DateUtilities.now() : existingDate);
customDate.setSeconds(0);
/***** Calendar Dialog Changes -- Start *****/
final CalendarDialog calendarDialog = new CalendarDialog(TaskEditActivity.this, customDate);
calendarDialog.show();
calendarDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface arg0) {
if (!cancelled) {
setDate(calendarDialog);
}
cancelled = false;
}
});
calendarDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
cancelled = true;
}
});
/***** Calendar Dialog Changes -- End *****/
/*DatePickerDialog datePicker = new DatePickerDialog(TaskEditActivity.this,
this, 1900 + customDate.getYear(), customDate.getMonth(), customDate.getDate());
datePicker.setOnCancelListener(this);
datePicker.show();*/
spinner.setSelection(previousSetting);
} else {
previousSetting = position;
model.setValue(Task.HIDE_UNTIL, item.date);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// ignore
}
Date customDate;
private void setDate(CalendarDialog calendarDialog) {
customDate = calendarDialog.getCalendarDate();
boolean specificTime = existingDateHour != SPECIFIC_DATE;
if(existingDateHour < 0) {
existingDateHour = customDate.getHours();
existingDateMinutes= customDate.getMinutes();
}
DeadlineTimePickerDialog timePicker = new DeadlineTimePickerDialog(TaskEditActivity.this, this,
existingDateHour, existingDateMinutes,
DateUtilities.is24HourFormat(TaskEditActivity.this),
specificTime);
timePicker.setOnCancelListener(this);
timePicker.show();
}
/*public void onDateSet(DatePicker view, int year, int month, int monthDay) {
customDate.setYear(year - 1900);
customDate.setMonth(month);
customDate.setDate(monthDay);
boolean specificTime = existingDateHour != SPECIFIC_DATE;
if(existingDateHour < 0) {
existingDateHour = customDate.getHours();
existingDateMinutes= customDate.getMinutes();
}
DeadlineTimePickerDialog timePicker = new DeadlineTimePickerDialog(TaskEditActivity.this, this,
existingDateHour, existingDateMinutes,
DateUtilities.is24HourFormat(TaskEditActivity.this),
specificTime);
timePicker.setOnCancelListener(this);
timePicker.show();
}*/
public void onTimeSet(TimePicker view, boolean hasTime, int hourOfDay, int minute) {
if(!hasTime) {
customDate.setHours(0);
customDate.setMinutes(0);
customDate.setSeconds(0);
} else {
customDate.setHours(hourOfDay);
customDate.setMinutes(minute);
existingDateHour = hourOfDay;
existingDateMinutes = minute;
}
customDateFinished();
}
@Override
public void onCancel(DialogInterface dialog) {
// user canceled, restore previous choice
spinner.setSelection(previousSetting);
}
private void customDateFinished() {
HideUntilValue[] list = createHideUntilList(customDate.getTime());
adapter = new ArrayAdapter<HideUntilValue>(
TaskEditActivity.this, android.R.layout.simple_spinner_item,
list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(0);
}
// --- setting up values
@Override
public void readFromTask(Task task) {
long date = task.getValue(Task.HIDE_UNTIL);
Date dueDay = new Date(task.getValue(Task.DUE_DATE)/1000L*1000L);
dueDay.setHours(0);
dueDay.setMinutes(0);
dueDay.setSeconds(0);
int selection = 0;
if(date == 0) {
selection = 0;
date = 0;
} else if(date == dueDay.getTime()) {
selection = 1;
date = 0;
} else if(date + DateUtilities.ONE_DAY == dueDay.getTime()) {
selection = 2;
date = 0;
} else if(date + DateUtilities.ONE_WEEK == dueDay.getTime()) {
selection = 3;
date = 0;
}
HideUntilValue[] list = createHideUntilList(date);
adapter = new ArrayAdapter<HideUntilValue>(
TaskEditActivity.this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(selection);
}
@Override
public String writeToModel(Task task) {
if(adapter == null || spinner == null)
return null;
HideUntilValue item = adapter.getItem(spinner.getSelectedItemPosition());
if(item == null)
return null;
long value = task.createHideUntil(item.setting, item.date);
task.setValue(Task.HIDE_UNTIL, value);
return null;
}
}
/**
* Control set dealing with reminder settings
*
* @author Tim Su <[email protected]>
*
*/
public class ReminderControlSet implements TaskEditControlSet {
private final CheckBox during, after;
private final Spinner mode;
public ReminderControlSet(int duringId, int afterId, int modeId) {
during = (CheckBox)findViewById(duringId);
after = (CheckBox)findViewById(afterId);
mode = (Spinner)findViewById(modeId);
String[] list = new String[] {
getString(R.string.TEA_reminder_alarm_off),
getString(R.string.TEA_reminder_alarm_on),
};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
TaskEditActivity.this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
runOnUiThread(new Runnable() {
@Override
public void run() {
mode.setAdapter(adapter);
}
});
}
public void setValue(int flags) {
during.setChecked((flags & Task.NOTIFY_AT_DEADLINE) > 0);
after.setChecked((flags &
Task.NOTIFY_AFTER_DEADLINE) > 0);
mode.setSelection((flags &
Task.NOTIFY_NONSTOP) > 0 ? 1 : 0);
}
public int getValue() {
int value = 0;
if(during.isChecked())
value |= Task.NOTIFY_AT_DEADLINE;
if(after.isChecked())
value |= Task.NOTIFY_AFTER_DEADLINE;
if(mode.getSelectedItemPosition() == 1)
value |= Task.NOTIFY_NONSTOP;
return value;
}
@Override
public void readFromTask(Task task) {
setValue(task.getValue(Task.REMINDER_FLAGS));
}
@Override
public String writeToModel(Task task) {
task.setValue(Task.REMINDER_FLAGS, getValue());
// clear snooze if task is being edited
task.setValue(Task.REMINDER_SNOOZE, 0L);
return null;
}
}
/**
* Control set dealing with random reminder settings
*
* @author Tim Su <[email protected]>
*
*/
public class RandomReminderControlSet implements TaskEditControlSet {
/** default interval for spinner if date is unselected */
private final long DEFAULT_INTERVAL = DateUtilities.ONE_WEEK * 2;
private final CheckBox settingCheckbox;
private final Spinner periodSpinner;
private boolean periodSpinnerInitialized = false;
private final int[] hours;
public RandomReminderControlSet(int settingCheckboxId, int periodButtonId) {
settingCheckbox = (CheckBox)findViewById(settingCheckboxId);
periodSpinner = (Spinner)findViewById(periodButtonId);
periodSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(periodSpinnerInitialized)
settingCheckbox.setChecked(true);
periodSpinnerInitialized = true;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// ignore
}
});
// create adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
TaskEditActivity.this, android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.TEA_reminder_random));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
periodSpinner.setAdapter(adapter);
// create hour array
String[] hourStrings = getResources().getStringArray(R.array.TEA_reminder_random_hours);
hours = new int[hourStrings.length];
for(int i = 0; i < hours.length; i++)
hours[i] = Integer.parseInt(hourStrings[i]);
}
@Override
public void readFromTask(Task task) {
long time = task.getValue(Task.REMINDER_PERIOD);
boolean enabled = time > 0;
if(time <= 0) {
time = DEFAULT_INTERVAL;
}
int i;
for(i = 0; i < hours.length - 1; i++)
if(hours[i] * DateUtilities.ONE_HOUR >= time)
break;
periodSpinner.setSelection(i);
settingCheckbox.setChecked(enabled);
}
@Override
public String writeToModel(Task task) {
if(settingCheckbox.isChecked()) {
int hourValue = hours[periodSpinner.getSelectedItemPosition()];
task.setValue(Task.REMINDER_PERIOD, hourValue * DateUtilities.ONE_HOUR);
} else
task.setValue(Task.REMINDER_PERIOD, 0L);
return null;
}
}
}
| false | true | private void setUpUIComponents() {
Resources r = getResources();
// set up tab host
TabHost tabHost = getTabHost();
tabHost.setPadding(0, 4, 0, 0);
LayoutInflater.from(this).inflate(R.layout.task_edit_activity,
tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_basic)).
setIndicator(r.getString(R.string.TEA_tab_basic),
r.getDrawable(R.drawable.tab_edit)).setContent(
R.id.tab_basic));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_extra)).
setIndicator(r.getString(R.string.TEA_tab_extra),
r.getDrawable(R.drawable.tab_advanced)).setContent(
R.id.tab_extra));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_addons)).
setIndicator(r.getString(R.string.TEA_tab_addons),
r.getDrawable(R.drawable.tab_addons)).setContent(
R.id.tab_addons));
getTabWidget().setBackgroundColor(Color.BLACK);
// populate control set
title = (EditText) findViewById(R.id.title);
controls.add(new EditTextControlSet(Task.TITLE, R.id.title));
controls.add(new ImportanceControlSet(R.id.importance_container));
controls.add(new UrgencyControlSet(R.id.urgency));
// prepare and set listener for voice-button
if(addOnService.hasPowerPack()) {
voiceAddNoteButton = (ImageButton) findViewById(R.id.voiceAddNoteButton);
voiceAddNoteButton.setVisibility(View.VISIBLE);
notesEditText = (EditText) findViewById(R.id.notes);
int prompt = R.string.voice_edit_note_prompt;
voiceNoteAssistant = new VoiceInputAssistant(this, voiceAddNoteButton,
notesEditText);
voiceNoteAssistant.setAppend(true);
voiceNoteAssistant.setLanguageModel(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voiceNoteAssistant.configureMicrophoneButton(prompt);
}
new Thread() {
@Override
public void run() {
AndroidUtilities.sleepDeep(500L);
runOnUiThread(new Runnable() {
public void run() {
// internal add-ins
controls.add(new TagsControlSet(TaskEditActivity.this, R.id.tags_container));
LinearLayout extrasAddons = (LinearLayout) findViewById(R.id.tab_extra_addons);
controls.add(new RepeatControlSet(TaskEditActivity.this, extrasAddons));
controls.add(new GCalControlSet(TaskEditActivity.this, extrasAddons));
LinearLayout addonsAddons = (LinearLayout) findViewById(R.id.tab_addons_addons);
try {
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
controls.add(new ProducteevControlSet(TaskEditActivity.this, addonsAddons));
notesEditText.setHint(R.string.producteev_TEA_notes);
((TextView)findViewById(R.id.notes_label)).setHint(R.string.producteev_TEA_notes);
}
} catch (Exception e) {
Log.e("astrid-error", "loading-control-set", e); //$NON-NLS-1$ //$NON-NLS-2$
}
controls.add(new TimerControlSet(TaskEditActivity.this, addonsAddons));
controls.add(new AlarmControlSet(TaskEditActivity.this, addonsAddons));
if(!addOnService.hasPowerPack()) {
// show add-on help if necessary
View addonsEmpty = findViewById(R.id.addons_empty);
addonsEmpty.setVisibility(View.VISIBLE);
addonsAddons.removeView(addonsEmpty);
addonsAddons.addView(addonsEmpty);
((Button)findViewById(R.id.addons_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addOnActivity = new Intent(TaskEditActivity.this, AddOnActivity.class);
addOnActivity.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true);
startActivity(addOnActivity);
}
});
}
controls.add( new ReminderControlSet(R.id.reminder_due,
R.id.reminder_overdue, R.id.reminder_alarm));
controls.add(new RandomReminderControlSet(R.id.reminder_random,
R.id.reminder_random_interval));
controls.add(new HideUntilControlSet(R.id.hideUntil));
// re-read all
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
});
notesControlSet = new EditTextControlSet(Task.NOTES, R.id.notes);
controls.add(notesControlSet);
// set up listeners
setUpListeners();
}
}.start();
}
| private void setUpUIComponents() {
Resources r = getResources();
// set up tab host
TabHost tabHost = getTabHost();
tabHost.setPadding(0, 4, 0, 0);
LayoutInflater.from(this).inflate(R.layout.task_edit_activity,
tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_basic)).
setIndicator(r.getString(R.string.TEA_tab_basic),
r.getDrawable(R.drawable.tab_edit)).setContent(
R.id.tab_basic));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_extra)).
setIndicator(r.getString(R.string.TEA_tab_extra),
r.getDrawable(R.drawable.tab_advanced)).setContent(
R.id.tab_extra));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_addons)).
setIndicator(r.getString(R.string.TEA_tab_addons),
r.getDrawable(R.drawable.tab_addons)).setContent(
R.id.tab_addons));
getTabWidget().setBackgroundColor(Color.BLACK);
// populate control set
title = (EditText) findViewById(R.id.title);
controls.add(new EditTextControlSet(Task.TITLE, R.id.title));
controls.add(new ImportanceControlSet(R.id.importance_container));
controls.add(new UrgencyControlSet(R.id.urgency));
notesEditText = (EditText) findViewById(R.id.notes);
// prepare and set listener for voice-button
if(addOnService.hasPowerPack()) {
voiceAddNoteButton = (ImageButton) findViewById(R.id.voiceAddNoteButton);
voiceAddNoteButton.setVisibility(View.VISIBLE);
int prompt = R.string.voice_edit_note_prompt;
voiceNoteAssistant = new VoiceInputAssistant(this, voiceAddNoteButton,
notesEditText);
voiceNoteAssistant.setAppend(true);
voiceNoteAssistant.setLanguageModel(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voiceNoteAssistant.configureMicrophoneButton(prompt);
}
new Thread() {
@Override
public void run() {
AndroidUtilities.sleepDeep(500L);
runOnUiThread(new Runnable() {
public void run() {
// internal add-ins
controls.add(new TagsControlSet(TaskEditActivity.this, R.id.tags_container));
LinearLayout extrasAddons = (LinearLayout) findViewById(R.id.tab_extra_addons);
controls.add(new RepeatControlSet(TaskEditActivity.this, extrasAddons));
controls.add(new GCalControlSet(TaskEditActivity.this, extrasAddons));
LinearLayout addonsAddons = (LinearLayout) findViewById(R.id.tab_addons_addons);
try {
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
controls.add(new ProducteevControlSet(TaskEditActivity.this, addonsAddons));
notesEditText.setHint(R.string.producteev_TEA_notes);
((TextView)findViewById(R.id.notes_label)).setHint(R.string.producteev_TEA_notes);
}
} catch (Exception e) {
Log.e("astrid-error", "loading-control-set", e); //$NON-NLS-1$ //$NON-NLS-2$
}
controls.add(new TimerControlSet(TaskEditActivity.this, addonsAddons));
controls.add(new AlarmControlSet(TaskEditActivity.this, addonsAddons));
if(!addOnService.hasPowerPack()) {
// show add-on help if necessary
View addonsEmpty = findViewById(R.id.addons_empty);
addonsEmpty.setVisibility(View.VISIBLE);
addonsAddons.removeView(addonsEmpty);
addonsAddons.addView(addonsEmpty);
((Button)findViewById(R.id.addons_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addOnActivity = new Intent(TaskEditActivity.this, AddOnActivity.class);
addOnActivity.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true);
startActivity(addOnActivity);
}
});
}
controls.add( new ReminderControlSet(R.id.reminder_due,
R.id.reminder_overdue, R.id.reminder_alarm));
controls.add(new RandomReminderControlSet(R.id.reminder_random,
R.id.reminder_random_interval));
controls.add(new HideUntilControlSet(R.id.hideUntil));
// re-read all
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
});
notesControlSet = new EditTextControlSet(Task.NOTES, R.id.notes);
controls.add(notesControlSet);
// set up listeners
setUpListeners();
}
}.start();
}
|
diff --git a/org.zend.php.common/src/org/zend/php/common/ToolTipHandler.java b/org.zend.php.common/src/org/zend/php/common/ToolTipHandler.java
index 795c2cf..250c543 100644
--- a/org.zend.php.common/src/org/zend/php/common/ToolTipHandler.java
+++ b/org.zend.php.common/src/org/zend/php/common/ToolTipHandler.java
@@ -1,260 +1,264 @@
package org.zend.php.common;
import java.net.URL;
import org.eclipse.equinox.internal.p2.discovery.AbstractCatalogSource;
import org.eclipse.equinox.internal.p2.discovery.model.CatalogItem;
import org.eclipse.equinox.internal.p2.ui.discovery.util.WorkbenchUtil;
import org.eclipse.equinox.internal.p2.ui.discovery.wizards.Messages;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
public class ToolTipHandler {
private Shell tipShell;
private Label tipLabelImage, tipLabelName, tipLabelText, tipLabelProvider;
private Widget tipWidget; // widget this tooltip is hovering over
private Point tipPosition; // the position being hovered over
Link link;
String url;
private int tipWidth = 250;
/**
* Creates a new tooltip handler
*
* @param parent
* the parent Shell
*/
public ToolTipHandler(Shell parent) {
createTooltip(parent);
}
private void createTooltip(Shell parent) {
Display display = parent.getDisplay();
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
gridLayout.marginWidth = 2;
gridLayout.marginHeight = 2;
tipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
tipShell.setLayout(gridLayout);
GridData gds = new GridData();
gds.widthHint = tipWidth;
tipShell.setLayoutData(gds);
tipShell.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage = new Label(tipShell, SWT.NONE);
tipLabelImage.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelImage.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL,
GridData.VERTICAL_ALIGN_BEGINNING, false, true, 1, 1));
tipLabelName = new Label(tipShell, SWT.NONE);
tipLabelName.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelName.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER));
FontData fd = tipLabelName.getFont().getFontData()[0];
fd.setStyle(SWT.BOLD);
tipLabelName.setFont(new Font(display, fd));
tipLabelText = new Label(tipShell, SWT.WRAP);
tipLabelText.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelText.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData textGD = new GridData();
textGD.widthHint = tipWidth;
textGD.horizontalSpan = 2;
tipLabelText.setLayoutData(textGD);
tipLabelProvider = new Label(tipShell, SWT.WRAP);
tipLabelProvider.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelProvider.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ GridData gd = new GridData();
+ gd.widthHint = tipWidth;
gd.horizontalSpan = 2;
tipLabelProvider.setLayoutData(gd);
link = new Link(tipShell, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false)
.align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- link.setLayoutData(gd);
+ GridData linkGD = new GridData();
+ linkGD.widthHint = tipWidth;
+ linkGD.horizontalSpan = 2;
+ link.setLayoutData(linkGD);
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil
.openUrl(url, IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
/**
* Enables customized hover help for a specified control
*
* @control the control on which to enable hoverhelp
*/
public void activateHoverHelp(final Control control) {
/*
* Get out of the way if we attempt to activate the control underneath
* the tooltip
*/
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
if (!tipShell.isDisposed() && tipShell.isVisible())
tipShell.setVisible(false);
}
});
/*
* Trap hover events to pop-up tooltip
*/
control.addMouseTrackListener(new MouseTrackAdapter() {
public void mouseExit(MouseEvent e) {
if (!tipShell.isDisposed() && tipShell.isVisible()) {
/*
* Check if the mouse exit happened because we move over the
* tooltip
*/
Rectangle containerBounds = tipShell.getBounds();
if (containerBounds.contains(Display.getCurrent()
.getCursorLocation())) {
return;
}
tipShell.setVisible(false);
tipWidget = null;
}
}
public void mouseHover(MouseEvent event) {
Point pt = new Point(event.x, event.y);
Widget widget = event.widget;
if (widget instanceof Tree) {
Tree w = (Tree) widget;
widget = w.getItem(pt);
}
if (widget == null) {
tipShell.setVisible(false);
tipWidget = null;
return;
}
if (widget == tipWidget)
return;
if (widget.getData() instanceof CatalogItem) {
tipWidget = widget;
if (control != null && !control.isDisposed())
showToolTip(control, pt, (CatalogItem) widget.getData());
}
}
});
}
private void showToolTip(final Control control, Point pt,
final CatalogItem ci) {
if (control == null || control.isDisposed() || tipLabelName == null
|| tipLabelName.isDisposed() || tipLabelText == null
|| tipLabelText.isDisposed()) {
createTooltip(control.getShell());
}
tipPosition = control.toDisplay(pt);
tipLabelName.setText(ci.getName().toString());
tipLabelText.setText(ci.getDescription());
String prov = "Provider: " + ci.getProvider();
tipLabelProvider.setText(prov);
Image image = computeImage(ci.getSource(), ci.getIcon().getImage16());
tipLabelImage.setImage(image); // accepts null
if (ci.getOverview() != null && ci.getOverview().getUrl() != null) {
url = ci.getOverview().getUrl();
link.setToolTipText(NLS.bind(
Messages.ConnectorDescriptorToolTip_detailsLink_tooltip, ci
.getOverview().getUrl()));
}
tipShell.pack();
setHoverLocation(tipShell, tipPosition);
tipShell.setVisible(true);
}
public static Image computeImage(AbstractCatalogSource discoverySource,
String imagePath) {
if (imagePath == null || imagePath.isEmpty()) {
return null;
}
URL resource = discoverySource.getResource(imagePath);
if (resource != null) {
ImageDescriptor descriptor = ImageDescriptor
.createFromURL(resource);
if (descriptor != null) {
return descriptor.createImage();
}
}
return null;
}
/**
* Sets the location for a hovering shell
*
* @param shell
* the object that is to hover
* @param position
* the position of a widget to hover over
* @return the top-left location for a hovering box
*/
private void setHoverLocation(Shell shell, Point position) {
Rectangle shellBounds = shell.getBounds();
Rectangle displayBounds = shell.getDisplay().getBounds();
shellBounds.x = Math.max(
Math.min(position.x, displayBounds.width - shellBounds.width),
0);
shellBounds.y = Math.max(
Math.min(position.y + 10, displayBounds.height
- shellBounds.height), 0);
shell.setBounds(shellBounds);
}
}
| false | true | private void createTooltip(Shell parent) {
Display display = parent.getDisplay();
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
gridLayout.marginWidth = 2;
gridLayout.marginHeight = 2;
tipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
tipShell.setLayout(gridLayout);
GridData gds = new GridData();
gds.widthHint = tipWidth;
tipShell.setLayoutData(gds);
tipShell.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage = new Label(tipShell, SWT.NONE);
tipLabelImage.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelImage.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL,
GridData.VERTICAL_ALIGN_BEGINNING, false, true, 1, 1));
tipLabelName = new Label(tipShell, SWT.NONE);
tipLabelName.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelName.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER));
FontData fd = tipLabelName.getFont().getFontData()[0];
fd.setStyle(SWT.BOLD);
tipLabelName.setFont(new Font(display, fd));
tipLabelText = new Label(tipShell, SWT.WRAP);
tipLabelText.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelText.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData textGD = new GridData();
textGD.widthHint = tipWidth;
textGD.horizontalSpan = 2;
tipLabelText.setLayoutData(textGD);
tipLabelProvider = new Label(tipShell, SWT.WRAP);
tipLabelProvider.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelProvider.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
tipLabelProvider.setLayoutData(gd);
link = new Link(tipShell, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false)
.align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
link.setLayoutData(gd);
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil
.openUrl(url, IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
| private void createTooltip(Shell parent) {
Display display = parent.getDisplay();
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
gridLayout.marginWidth = 2;
gridLayout.marginHeight = 2;
tipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
tipShell.setLayout(gridLayout);
GridData gds = new GridData();
gds.widthHint = tipWidth;
tipShell.setLayoutData(gds);
tipShell.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage = new Label(tipShell, SWT.NONE);
tipLabelImage.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelImage.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelImage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL,
GridData.VERTICAL_ALIGN_BEGINNING, false, true, 1, 1));
tipLabelName = new Label(tipShell, SWT.NONE);
tipLabelName.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelName.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tipLabelName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER));
FontData fd = tipLabelName.getFont().getFontData()[0];
fd.setStyle(SWT.BOLD);
tipLabelName.setFont(new Font(display, fd));
tipLabelText = new Label(tipShell, SWT.WRAP);
tipLabelText.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelText.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData textGD = new GridData();
textGD.widthHint = tipWidth;
textGD.horizontalSpan = 2;
tipLabelText.setLayoutData(textGD);
tipLabelProvider = new Label(tipShell, SWT.WRAP);
tipLabelProvider.setForeground(display
.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tipLabelProvider.setBackground(display
.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData gd = new GridData();
gd.widthHint = tipWidth;
gd.horizontalSpan = 2;
tipLabelProvider.setLayoutData(gd);
link = new Link(tipShell, SWT.NULL);
GridDataFactory.fillDefaults().grab(false, false)
.align(SWT.BEGINNING, SWT.CENTER).applyTo(link);
link.setText(Messages.ConnectorDescriptorToolTip_detailsLink);
link.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridData linkGD = new GridData();
linkGD.widthHint = tipWidth;
linkGD.horizontalSpan = 2;
link.setLayoutData(linkGD);
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WorkbenchUtil
.openUrl(url, IWorkbenchBrowserSupport.AS_EXTERNAL);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
|
diff --git a/src/org/openstreetmap/josm/actions/AboutAction.java b/src/org/openstreetmap/josm/actions/AboutAction.java
index bdb067a7..667eed9a 100644
--- a/src/org/openstreetmap/josm/actions/AboutAction.java
+++ b/src/org/openstreetmap/josm/actions/AboutAction.java
@@ -1,218 +1,216 @@
//License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.actions;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Properties;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.plugins.PluginHandler;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.UrlLabel;
import org.openstreetmap.josm.tools.Shortcut;
/**
* Nice about screen. I guess every application need one these days.. *sigh*
*
* The REVISION resource is read and if present, it shows the revision
* information of the jar-file.
*
* @author imi
*/
/**
* @author Stephan
*
*/
public class AboutAction extends JosmAction {
private static final String version;
private final static JTextArea revision;
private static String time;
static {
boolean manifest = false;
URL u = Main.class.getResource("/REVISION");
if(u == null) {
try {
manifest = true;
u = new URL("jar:" + Main.class.getProtectionDomain().getCodeSource().getLocation().toString()
+ "!/META-INF/MANIFEST.MF");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
revision = loadFile(u, manifest);
Pattern versionPattern = Pattern.compile(".*?(?:Revision|Main-Version): ([0-9]*(?: SVN)?).*", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher match = versionPattern.matcher(revision.getText());
version = match.matches() ? match.group(1) : tr("UNKNOWN");
Pattern timePattern = Pattern.compile(".*?(?:Last Changed Date|Main-Date): ([^\n]*).*", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
match = timePattern.matcher(revision.getText());
time = match.matches() ? match.group(1) : tr("UNKNOWN");
}
/**
* Return string describing version.
* Note that the strinc contains the version number plus an optional suffix of " SVN" to indicate an unofficial development build.
* @return version string
*/
static public String getVersionString() {
return version;
}
static public String getTextBlock() {
return revision.getText();
}
static public void setUserAgent() {
Properties sysProp = System.getProperties();
sysProp.put("http.agent", "JOSM/1.5 ("+(version.equals(tr("UNKNOWN"))?"UNKNOWN":version)+" "+Main.getLanguageCode()+")");
System.setProperties(sysProp);
}
/**
* Return the number part of the version string.
* @return integer part of version number or Integer.MAX_VALUE if not available
*/
public static int getVersionNumber() {
int myVersion=Integer.MAX_VALUE;
try {
myVersion = Integer.parseInt(version.split(" ")[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return myVersion;
}
/**
* check whether the version is a development build out of SVN.
* @return true if it is a SVN unofficial build
*/
public static boolean isDevelopmentVersion() {
return version.endsWith(" SVN") || version.equals(tr("UNKNOWN"));
}
public AboutAction() {
super(tr("About"), "about", tr("Display the about screen."), Shortcut.registerShortcut("system:about", tr("About"), KeyEvent.VK_F1, Shortcut.GROUP_DIRECT, Shortcut.SHIFT_DEFAULT), true);
}
public void actionPerformed(ActionEvent e) {
JTabbedPane about = new JTabbedPane();
JTextArea readme = loadFile(Main.class.getResource("/README"), false);
JTextArea contribution = loadFile(Main.class.getResource("/CONTRIBUTION"), false);
JPanel info = new JPanel(new GridBagLayout());
JLabel caption = new JLabel("JOSM - " + tr("Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
info.add(caption, GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Version {0}",version)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Last change at {0}",time)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Java Version {0}",System.getProperty("java.version"))), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Homepage")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de"), GBC.eol().fill(GBC.HORIZONTAL));
info.add(new JLabel(tr("Bug Reports")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eol().fill(GBC.HORIZONTAL));
- info.add(new JLabel(tr("News about JOSM")), GBC.std().insets(10,0,10,0));
- info.add(new UrlLabel("http://www.opengeodata.org/?cat=17"), GBC.eol().fill(GBC.HORIZONTAL));
about.addTab(tr("Info"), info);
about.addTab(tr("Readme"), createScrollPane(readme));
about.addTab(tr("Revision"), createScrollPane(revision));
about.addTab(tr("Contribution"), createScrollPane(contribution));
about.addTab(tr("Plugins"), new JScrollPane(PluginHandler.getInfoPanel()));
about.setPreferredSize(new Dimension(500,300));
JOptionPane.showMessageDialog(Main.parent, about, tr("About JOSM..."),
JOptionPane.INFORMATION_MESSAGE, ImageProvider.get("logo"));
}
private JScrollPane createScrollPane(JTextArea area) {
area.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
area.setOpaque(false);
JScrollPane sp = new JScrollPane(area);
sp.setBorder(null);
sp.setOpaque(false);
return sp;
}
/**
* Retrieve the latest JOSM version from the JOSM homepage.
* @return An string with the latest version or "UNKNOWN" in case
* of problems (e.g. no internet connection).
*/
public static String checkLatestVersion() {
String latest;
try {
InputStream s = new URL("http://josm.openstreetmap.de/current").openStream();
latest = new BufferedReader(new InputStreamReader(s)).readLine();
s.close();
} catch (IOException x) {
x.printStackTrace();
return tr("UNKNOWN");
}
return latest;
}
/**
* Load the specified resource into an TextArea and return it.
* @param resource The resource url to load
* @return An read-only text area with the content of "resource"
*/
private static JTextArea loadFile(URL resource, boolean manifest) {
JTextArea area = new JTextArea(tr("File could not be found."));
area.setEditable(false);
Font font = Font.getFont("monospaced");
if (font != null)
area.setFont(font);
if (resource == null)
return area;
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(resource.openStream()));
String s = "";
for (String line = in.readLine(); line != null; line = in.readLine())
s += line + "\n";
if(manifest)
{
s = Pattern.compile("\n ", Pattern.DOTALL).matcher(s).replaceAll("");
s = Pattern.compile("^(SHA1-Digest|Name): .*?$", Pattern.DOTALL|Pattern.MULTILINE).matcher(s).replaceAll("");
s = Pattern.compile("\n+$", Pattern.DOTALL).matcher(s).replaceAll("");
}
area.setText(s);
area.setCaretPosition(0);
} catch (IOException e) {
e.printStackTrace();
}
return area;
}
}
| true | true | public void actionPerformed(ActionEvent e) {
JTabbedPane about = new JTabbedPane();
JTextArea readme = loadFile(Main.class.getResource("/README"), false);
JTextArea contribution = loadFile(Main.class.getResource("/CONTRIBUTION"), false);
JPanel info = new JPanel(new GridBagLayout());
JLabel caption = new JLabel("JOSM - " + tr("Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
info.add(caption, GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Version {0}",version)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Last change at {0}",time)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Java Version {0}",System.getProperty("java.version"))), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Homepage")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de"), GBC.eol().fill(GBC.HORIZONTAL));
info.add(new JLabel(tr("Bug Reports")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eol().fill(GBC.HORIZONTAL));
info.add(new JLabel(tr("News about JOSM")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://www.opengeodata.org/?cat=17"), GBC.eol().fill(GBC.HORIZONTAL));
about.addTab(tr("Info"), info);
about.addTab(tr("Readme"), createScrollPane(readme));
about.addTab(tr("Revision"), createScrollPane(revision));
about.addTab(tr("Contribution"), createScrollPane(contribution));
about.addTab(tr("Plugins"), new JScrollPane(PluginHandler.getInfoPanel()));
about.setPreferredSize(new Dimension(500,300));
JOptionPane.showMessageDialog(Main.parent, about, tr("About JOSM..."),
JOptionPane.INFORMATION_MESSAGE, ImageProvider.get("logo"));
}
| public void actionPerformed(ActionEvent e) {
JTabbedPane about = new JTabbedPane();
JTextArea readme = loadFile(Main.class.getResource("/README"), false);
JTextArea contribution = loadFile(Main.class.getResource("/CONTRIBUTION"), false);
JPanel info = new JPanel(new GridBagLayout());
JLabel caption = new JLabel("JOSM - " + tr("Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
info.add(caption, GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Version {0}",version)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Last change at {0}",time)), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,5), GBC.eol());
info.add(new JLabel(tr("Java Version {0}",System.getProperty("java.version"))), GBC.eol().fill(GBC.HORIZONTAL).insets(10,0,0,0));
info.add(GBC.glue(0,10), GBC.eol());
info.add(new JLabel(tr("Homepage")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de"), GBC.eol().fill(GBC.HORIZONTAL));
info.add(new JLabel(tr("Bug Reports")), GBC.std().insets(10,0,10,0));
info.add(new UrlLabel("http://josm.openstreetmap.de/newticket"), GBC.eol().fill(GBC.HORIZONTAL));
about.addTab(tr("Info"), info);
about.addTab(tr("Readme"), createScrollPane(readme));
about.addTab(tr("Revision"), createScrollPane(revision));
about.addTab(tr("Contribution"), createScrollPane(contribution));
about.addTab(tr("Plugins"), new JScrollPane(PluginHandler.getInfoPanel()));
about.setPreferredSize(new Dimension(500,300));
JOptionPane.showMessageDialog(Main.parent, about, tr("About JOSM..."),
JOptionPane.INFORMATION_MESSAGE, ImageProvider.get("logo"));
}
|
diff --git a/web/src/main/java/org/fao/geonet/guiservices/metadata/Sitemap.java b/web/src/main/java/org/fao/geonet/guiservices/metadata/Sitemap.java
index c5a677e864..f5c4f9ef9b 100644
--- a/web/src/main/java/org/fao/geonet/guiservices/metadata/Sitemap.java
+++ b/web/src/main/java/org/fao/geonet/guiservices/metadata/Sitemap.java
@@ -1,92 +1,92 @@
//==============================================================================
//===
//=== Sitemap
//===
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== 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 St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.guiservices.metadata;
import jeeves.interfaces.Service;
import jeeves.resources.dbms.Dbms;
import jeeves.server.ServiceConfig;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Util;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.kernel.AccessManager;
import org.jdom.Element;
import java.util.Set;
/**
* Create a sitemap document with metadata records
*
* Formats: xml (default if not specified), html
*
* See http://www.sitemaps.org/protocol.php
*/
public class Sitemap implements Service
{
private final String FORMAT_XML = "xml";
private final String FORMAT_HTML = "html";
public void init(String appPath, ServiceConfig config) throws Exception { }
public Element exec(Element params, ServiceContext context) throws Exception
{
String format = Util.getParam(params, "format", FORMAT_XML);
if (!((format.equalsIgnoreCase(FORMAT_HTML)) ||
(format.equalsIgnoreCase(FORMAT_XML)))) {
format = FORMAT_XML;
}
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
AccessManager am = gc.getAccessManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
- Set<String> groups = am.getUserGroups(dbms, context.getUserSession(), context.getIpAddress());
+ Set<String> groups = am.getUserGroups(dbms, context.getUserSession(), context.getIpAddress(), false);
String query = "SELECT DISTINCT id, uuid, schemaId, changeDate FROM Metadata, OperationAllowed "+
"WHERE id=metadataId AND isTemplate='n' AND operationId=0 AND (";
String aux = "";
for (String grpId : groups)
aux += " OR groupId="+grpId;
query += aux.substring(4);
query += ") ORDER BY changeDate DESC";
Element result = dbms.select(query);
Element formatEl = new Element("format");
formatEl.setText(format.toLowerCase());
result.addContent(formatEl);
return result;
}
}
| true | true | public Element exec(Element params, ServiceContext context) throws Exception
{
String format = Util.getParam(params, "format", FORMAT_XML);
if (!((format.equalsIgnoreCase(FORMAT_HTML)) ||
(format.equalsIgnoreCase(FORMAT_XML)))) {
format = FORMAT_XML;
}
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
AccessManager am = gc.getAccessManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
Set<String> groups = am.getUserGroups(dbms, context.getUserSession(), context.getIpAddress());
String query = "SELECT DISTINCT id, uuid, schemaId, changeDate FROM Metadata, OperationAllowed "+
"WHERE id=metadataId AND isTemplate='n' AND operationId=0 AND (";
String aux = "";
for (String grpId : groups)
aux += " OR groupId="+grpId;
query += aux.substring(4);
query += ") ORDER BY changeDate DESC";
Element result = dbms.select(query);
Element formatEl = new Element("format");
formatEl.setText(format.toLowerCase());
result.addContent(formatEl);
return result;
}
| public Element exec(Element params, ServiceContext context) throws Exception
{
String format = Util.getParam(params, "format", FORMAT_XML);
if (!((format.equalsIgnoreCase(FORMAT_HTML)) ||
(format.equalsIgnoreCase(FORMAT_XML)))) {
format = FORMAT_XML;
}
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
AccessManager am = gc.getAccessManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
Set<String> groups = am.getUserGroups(dbms, context.getUserSession(), context.getIpAddress(), false);
String query = "SELECT DISTINCT id, uuid, schemaId, changeDate FROM Metadata, OperationAllowed "+
"WHERE id=metadataId AND isTemplate='n' AND operationId=0 AND (";
String aux = "";
for (String grpId : groups)
aux += " OR groupId="+grpId;
query += aux.substring(4);
query += ") ORDER BY changeDate DESC";
Element result = dbms.select(query);
Element formatEl = new Element("format");
formatEl.setText(format.toLowerCase());
result.addContent(formatEl);
return result;
}
|
diff --git a/Temp/src/main/MainForm.java b/Temp/src/main/MainForm.java
index 0e505ef..b134be2 100644
--- a/Temp/src/main/MainForm.java
+++ b/Temp/src/main/MainForm.java
@@ -1,652 +1,650 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* MainForm.java
*
* Created on Nov 26, 2011, 2:53:07 PM
*/
package main;
import OR.Matrix;
import OR.SimplexProblem;
import OR.SolutionList;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import sun.util.logging.resources.logging;
/**
*
* @author mhd
*/
public class MainForm extends javax.swing.JFrame {
/** Creates new form MainForm */
public MainForm() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
tabC = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
lblZstatement = new javax.swing.JLabel();
cbMaxMin = new javax.swing.JComboBox();
jScrollPane4 = new javax.swing.JScrollPane();
tabTable = new javax.swing.JTable();
jScrollPane5 = new javax.swing.JScrollPane();
tabSolutions = new javax.swing.JTable();
jLabel7 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btnRemoveVar = new javax.swing.JButton();
btnAddVar = new javax.swing.JButton();
btnRemoveCondition = new javax.swing.JButton();
btnAddCondition = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btnSolve = new javax.swing.JButton();
lblTime = new javax.swing.JLabel();
lblSolType = new javax.swing.JLabel();
lblResult = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
scrollLegalForm = new javax.swing.JScrollPane();
txtLegalForm = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabConditions = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
tabB = new javax.swing.JTable();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
tabC.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabC.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane2.setViewportView(tabC);
jLabel1.setText("C =");
lblZstatement.setText("maxZ = C . X");
cbMaxMin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Max", "Min" }));
cbMaxMin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbMaxMinActionPerformed(evt);
}
});
tabTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
" ", "Z", "X1", "X2", "X3", "X4", "RHS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane4.setViewportView(tabTable);
tabSolutions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Z", "X1", "X2", "X3"
}
));
jScrollPane5.setViewportView(tabSolutions);
jLabel7.setText("Table :");
btnRemoveVar.setText("-");
btnRemoveVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveVarActionPerformed(evt);
}
});
btnAddVar.setText("+");
btnAddVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddVarActionPerformed(evt);
}
});
btnRemoveCondition.setText("-");
btnRemoveCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveConditionActionPerformed(evt);
}
});
btnAddCondition.setText("+");
btnAddCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddConditionActionPerformed(evt);
}
});
jLabel4.setText("Variables");
jLabel6.setText("Conditions");
btnSolve.setText("Solve");
btnSolve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSolveActionPerformed(evt);
}
});
lblTime.setText("Time : ?");
lblSolType.setText("Solution Type : ?");
lblResult.setText("لا توجد بيانات بعد");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(10, 10, 10)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddVar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRemoveVar)
- .addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))
+ .addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))
.addGap(49, 49, 49))
.addComponent(btnSolve, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(2, 2, 2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblSolType)
.addGap(251, 251, 251)
.addComponent(lblResult))
.addComponent(lblTime))
- .addGap(330, 330, 330))
+ .addGap(382, 382, 382))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddCondition, btnAddVar, btnRemoveCondition, btnRemoveVar});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRemoveVar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblSolType))
.addComponent(btnAddVar, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
.addComponent(jLabel6))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(btnSolve))
.addComponent(lblTime)))
.addComponent(lblResult))
.addContainerGap())
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAddCondition, btnAddVar});
jLabel3.setText("Solutions :");
scrollLegalForm.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
- scrollLegalForm.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
txtLegalForm.setColumns(20);
txtLegalForm.setEditable(false);
txtLegalForm.setRows(5);
txtLegalForm.setTabSize(4);
txtLegalForm.setText("Legal From:\n\tZ=C.X\nsubjected to :\n\t---------\n \t---------\n\t---------");
txtLegalForm.setAutoscrolls(false);
scrollLegalForm.setViewportView(txtLegalForm);
tabConditions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabConditions.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane1.setViewportView(tabConditions);
tabB.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null},
{null},
{null},
{null}
},
new String [] {
"b"
}
) {
Class[] types = new Class [] {
java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane3.setViewportView(tabB);
jLabel5.setText("subjected to : ");
jLabel2.setText("A = ");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(34, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
- .addComponent(jLabel2)
- .addGap(146, 146, 146))
+ .addComponent(jLabel2))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)))
- .addContainerGap())
+ .addGap(17, 17, 17))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(lblZstatement)
.addGap(298, 298, 298)
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99)
.addComponent(jLabel7))
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollLegalForm)))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblZstatement))
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel7)))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70)
.addComponent(jLabel3)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scrollLegalForm, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
- .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAddVarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddVarActionPerformed
// TODO add your handling code here:
TableColumn newCol = new TableColumn();
newCol.setHeaderValue("X" + (tabConditions.getColumnCount() + 1));
tabConditions.addColumn(newCol);
newCol = new TableColumn();
newCol.setHeaderValue("X" + (tabC.getColumnCount() + 1));
tabC.addColumn(newCol);
newCol = new TableColumn();
newCol.setHeaderValue("X" + (tabSolutions.getColumnCount() + 1));
tabSolutions.addColumn(newCol);
}//GEN-LAST:event_btnAddVarActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
// TODO add your handling code here:
}//GEN-LAST:event_formComponentShown
private void cbMaxMinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMaxMinActionPerformed
// TODO add your handling code here:
lblZstatement.setText(cbMaxMin.getSelectedItem().toString().toLowerCase() + "Z = C . X");
}//GEN-LAST:event_cbMaxMinActionPerformed
private void btnAddConditionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddConditionActionPerformed
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) tabConditions.getModel();
model.addRow(new java.util.Vector<Object>());
model = (DefaultTableModel) tabB.getModel();
model.addRow(new java.util.Vector<Object>());
}//GEN-LAST:event_btnAddConditionActionPerformed
private void btnRemoveConditionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveConditionActionPerformed
DefaultTableModel model = (DefaultTableModel) tabConditions.getModel();
int count = tabConditions.getRowCount();
model.removeRow(count-1);
model = (DefaultTableModel) tabB.getModel();
model.removeRow(count-1);
System.out.println(tabConditions.getRowCount());
}//GEN-LAST:event_btnRemoveConditionActionPerformed
private void btnRemoveVarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveVarActionPerformed
// TODO add your handling code here:
int count = tabConditions.getColumnCount();
tabConditions.getColumnModel().removeColumn(tabConditions.getColumn("X" + (count)));
tabC.getColumnModel().removeColumn(tabC.getColumn("X" + (count)));
System.out.println(tabConditions.getColumnCount());
}//GEN-LAST:event_btnRemoveVarActionPerformed
private double[][] Vector2doubleArray(Vector<Vector<Double>> a) {
int n = tabConditions.getColumnCount();
int m = tabConditions.getRowCount();
double[][] doubles = new double[m][n];
for (int i=0;i<m;i++) {
for (int j=0;j<n;j++)
doubles[i][j] = a.get(i).get(j);
}
return doubles;
}
private Double[][] Vector2DoubleArray(Vector<Vector<Double>> a) {
int n = tabConditions.getColumnCount();
int m = tabConditions.getRowCount();
Double[][] doubles = new Double[m][n];
for (int i=0;i<m;i++) {
for (int j=0;j<n;j++)
doubles[i][j] = a.get(i).get(j);
}
return doubles;
}
private double[][] getDataFromTable(JTable table) {
int n = table.getColumnCount();
int m = table.getRowCount();
double[][] doubles = new double[m][n];
for (int i=0;i<m;i++) {
for (int j=0;j<n;j++)
doubles[i][j] = ((Double)table.getValueAt(i, j)).doubleValue();
}
return doubles;
}
private static Double[] double2Double(double[] a) {
Double[] doubles = new Double[a.length];
for (int i=0;i<a.length;i++) {
doubles[i] = a[i];
}
return doubles;
}
private void btnSolveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolveActionPerformed
// TODO add your handling code here:
try{
double[][] A = getDataFromTable(tabConditions);
double[] C = getDataFromTable(tabC)[0];
double[] b = new Matrix(getDataFromTable(tabB)).transpose().getArray()[0];
SimplexProblem problem = new SimplexProblem(SimplexProblem.ProblemType.valueOf(cbMaxMin.getSelectedItem().toString()),
A, double2Double(C), double2Double(b));
txtLegalForm.setText(problem.getLegalFormAsText());
SolutionList list = problem.solveByTableSimplex();
DefaultTableModel model;
model = (DefaultTableModel)tabSolutions.getModel();
while (list.getLength() > tabSolutions.getColumnCount()) {
TableColumn newCol = new TableColumn(model.getColumnCount());
newCol.setHeaderValue("X" + (tabSolutions.getColumnCount()));
tabSolutions.setAutoCreateColumnsFromModel(false);
tabSolutions.addColumn(newCol);
model.addColumn("X" + (tabSolutions.getColumnCount()));
}
while (list.getLength() < tabSolutions.getColumnCount()) {
tabSolutions.removeColumn(tabSolutions.getColumn("X" + (tabSolutions.getColumnCount()-1)));
}
if (model.getRowCount() >= 1) {
model.setRowCount(0);
}
for (int i=0;i<list.size();i++) {
Double[] row = list.get(i);
model.addRow(row);
}
// adding table
String[] names = new String[list.getLength()+2];
names[0] = "Basic";
names[1] = "Z";
names[names.length-1]="RHS";
for (int i=2;i<names.length-1;i++)
names[i] = "X" + i;
Matrix allTable = list.table.getTable();
model = new DefaultTableModel(names, allTable.getRowDimension());
for (int i=0;i<allTable.getRowDimension();i++) {
for (int j=0;j<allTable.getColumnDimension();j++)
model.setValueAt(allTable.get(i, j), i, j);
}
model.setValueAt("Z", 0, 0);
for (int i=1 ;i<allTable.getRowDimension();i++){
int num = (int)allTable.get(i, 0);
String name = "X" + num;
model.setValueAt(name, i, 0);
}
tabTable.setModel(model);
lblTime.setText("Time : \n" + list.time + " ns");
lblSolType.setText("Solution Type : " + list.getType());
if (list.getType() == SolutionList.SolutionType.InfinityOfOptimalSolutions)
lblResult.setText("الحل تركيب خطي من الحلول التالية");
else if (list.getType() == SolutionList.SolutionType.Unlimited)
lblResult.setText("لا توجد حلول");
else if (list.getType() == SolutionList.SolutionType.OneOptimalSolution)
lblResult.setText("حل وحيد أمثلي");
}
catch (NullPointerException e) {
JOptionPane.showMessageDialog(this, "Wrong Input !! .. did you enter all the boxes ? .. any Boxes under edit now ?");
}
}//GEN-LAST:event_btnSolveActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAddCondition;
private javax.swing.JButton btnAddVar;
private javax.swing.JButton btnRemoveCondition;
private javax.swing.JButton btnRemoveVar;
private javax.swing.JButton btnSolve;
private javax.swing.JComboBox cbMaxMin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JLabel lblResult;
private javax.swing.JLabel lblSolType;
private javax.swing.JLabel lblTime;
private javax.swing.JLabel lblZstatement;
private javax.swing.JScrollPane scrollLegalForm;
private javax.swing.JTable tabB;
private javax.swing.JTable tabC;
private javax.swing.JTable tabConditions;
private javax.swing.JTable tabSolutions;
private javax.swing.JTable tabTable;
private javax.swing.JTextArea txtLegalForm;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
tabC = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
lblZstatement = new javax.swing.JLabel();
cbMaxMin = new javax.swing.JComboBox();
jScrollPane4 = new javax.swing.JScrollPane();
tabTable = new javax.swing.JTable();
jScrollPane5 = new javax.swing.JScrollPane();
tabSolutions = new javax.swing.JTable();
jLabel7 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btnRemoveVar = new javax.swing.JButton();
btnAddVar = new javax.swing.JButton();
btnRemoveCondition = new javax.swing.JButton();
btnAddCondition = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btnSolve = new javax.swing.JButton();
lblTime = new javax.swing.JLabel();
lblSolType = new javax.swing.JLabel();
lblResult = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
scrollLegalForm = new javax.swing.JScrollPane();
txtLegalForm = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabConditions = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
tabB = new javax.swing.JTable();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
tabC.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabC.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane2.setViewportView(tabC);
jLabel1.setText("C =");
lblZstatement.setText("maxZ = C . X");
cbMaxMin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Max", "Min" }));
cbMaxMin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbMaxMinActionPerformed(evt);
}
});
tabTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
" ", "Z", "X1", "X2", "X3", "X4", "RHS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane4.setViewportView(tabTable);
tabSolutions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Z", "X1", "X2", "X3"
}
));
jScrollPane5.setViewportView(tabSolutions);
jLabel7.setText("Table :");
btnRemoveVar.setText("-");
btnRemoveVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveVarActionPerformed(evt);
}
});
btnAddVar.setText("+");
btnAddVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddVarActionPerformed(evt);
}
});
btnRemoveCondition.setText("-");
btnRemoveCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveConditionActionPerformed(evt);
}
});
btnAddCondition.setText("+");
btnAddCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddConditionActionPerformed(evt);
}
});
jLabel4.setText("Variables");
jLabel6.setText("Conditions");
btnSolve.setText("Solve");
btnSolve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSolveActionPerformed(evt);
}
});
lblTime.setText("Time : ?");
lblSolType.setText("Solution Type : ?");
lblResult.setText("لا توجد بيانات بعد");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(10, 10, 10)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddVar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRemoveVar)
.addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))
.addGap(49, 49, 49))
.addComponent(btnSolve, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(2, 2, 2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblSolType)
.addGap(251, 251, 251)
.addComponent(lblResult))
.addComponent(lblTime))
.addGap(330, 330, 330))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddCondition, btnAddVar, btnRemoveCondition, btnRemoveVar});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRemoveVar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblSolType))
.addComponent(btnAddVar, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnSolve))
.addComponent(lblTime)))
.addComponent(lblResult))
.addContainerGap())
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAddCondition, btnAddVar});
jLabel3.setText("Solutions :");
scrollLegalForm.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollLegalForm.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
txtLegalForm.setColumns(20);
txtLegalForm.setEditable(false);
txtLegalForm.setRows(5);
txtLegalForm.setTabSize(4);
txtLegalForm.setText("Legal From:\n\tZ=C.X\nsubjected to :\n\t---------\n \t---------\n\t---------");
txtLegalForm.setAutoscrolls(false);
scrollLegalForm.setViewportView(txtLegalForm);
tabConditions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabConditions.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane1.setViewportView(tabConditions);
tabB.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null},
{null},
{null},
{null}
},
new String [] {
"b"
}
) {
Class[] types = new Class [] {
java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane3.setViewportView(tabB);
jLabel5.setText("subjected to : ");
jLabel2.setText("A = ");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(34, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addGap(146, 146, 146))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(lblZstatement)
.addGap(298, 298, 298)
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99)
.addComponent(jLabel7))
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollLegalForm)))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblZstatement))
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel7)))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70)
.addComponent(jLabel3)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scrollLegalForm, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
tabC = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
lblZstatement = new javax.swing.JLabel();
cbMaxMin = new javax.swing.JComboBox();
jScrollPane4 = new javax.swing.JScrollPane();
tabTable = new javax.swing.JTable();
jScrollPane5 = new javax.swing.JScrollPane();
tabSolutions = new javax.swing.JTable();
jLabel7 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btnRemoveVar = new javax.swing.JButton();
btnAddVar = new javax.swing.JButton();
btnRemoveCondition = new javax.swing.JButton();
btnAddCondition = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btnSolve = new javax.swing.JButton();
lblTime = new javax.swing.JLabel();
lblSolType = new javax.swing.JLabel();
lblResult = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
scrollLegalForm = new javax.swing.JScrollPane();
txtLegalForm = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabConditions = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
tabB = new javax.swing.JTable();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
tabC.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabC.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane2.setViewportView(tabC);
jLabel1.setText("C =");
lblZstatement.setText("maxZ = C . X");
cbMaxMin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Max", "Min" }));
cbMaxMin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbMaxMinActionPerformed(evt);
}
});
tabTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
" ", "Z", "X1", "X2", "X3", "X4", "RHS"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane4.setViewportView(tabTable);
tabSolutions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Z", "X1", "X2", "X3"
}
));
jScrollPane5.setViewportView(tabSolutions);
jLabel7.setText("Table :");
btnRemoveVar.setText("-");
btnRemoveVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveVarActionPerformed(evt);
}
});
btnAddVar.setText("+");
btnAddVar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddVarActionPerformed(evt);
}
});
btnRemoveCondition.setText("-");
btnRemoveCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveConditionActionPerformed(evt);
}
});
btnAddCondition.setText("+");
btnAddCondition.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddConditionActionPerformed(evt);
}
});
jLabel4.setText("Variables");
jLabel6.setText("Conditions");
btnSolve.setText("Solve");
btnSolve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSolveActionPerformed(evt);
}
});
lblTime.setText("Time : ?");
lblSolType.setText("Solution Type : ?");
lblResult.setText("لا توجد بيانات بعد");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(10, 10, 10)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddVar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRemoveVar)
.addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))
.addGap(49, 49, 49))
.addComponent(btnSolve, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(2, 2, 2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblSolType)
.addGap(251, 251, 251)
.addComponent(lblResult))
.addComponent(lblTime))
.addGap(382, 382, 382))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddCondition, btnAddVar, btnRemoveCondition, btnRemoveVar});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRemoveVar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblSolType))
.addComponent(btnAddVar, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnRemoveCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
.addComponent(btnAddCondition, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(btnSolve))
.addComponent(lblTime)))
.addComponent(lblResult))
.addContainerGap())
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAddCondition, btnAddVar});
jLabel3.setText("Solutions :");
scrollLegalForm.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
txtLegalForm.setColumns(20);
txtLegalForm.setEditable(false);
txtLegalForm.setRows(5);
txtLegalForm.setTabSize(4);
txtLegalForm.setText("Legal From:\n\tZ=C.X\nsubjected to :\n\t---------\n \t---------\n\t---------");
txtLegalForm.setAutoscrolls(false);
scrollLegalForm.setViewportView(txtLegalForm);
tabConditions.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"X1", "X2", "X3", "X4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tabConditions.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
jScrollPane1.setViewportView(tabConditions);
tabB.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null},
{null},
{null},
{null}
},
new String [] {
"b"
}
) {
Class[] types = new Class [] {
java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane3.setViewportView(tabB);
jLabel5.setText("subjected to : ");
jLabel2.setText("A = ");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(34, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel2))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)))
.addGap(17, 17, 17))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(lblZstatement)
.addGap(298, 298, 298)
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99)
.addComponent(jLabel7))
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollLegalForm)))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblZstatement))
.addComponent(cbMaxMin, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel7)))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70)
.addComponent(jLabel3)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scrollLegalForm, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/Java/de/Keyle/MyPet/gui/skillcreator/SkilltreeCreator.java b/src/Java/de/Keyle/MyPet/gui/skillcreator/SkilltreeCreator.java
index e7d7aacbf..4fa542d44 100644
--- a/src/Java/de/Keyle/MyPet/gui/skillcreator/SkilltreeCreator.java
+++ b/src/Java/de/Keyle/MyPet/gui/skillcreator/SkilltreeCreator.java
@@ -1,568 +1,568 @@
/*
* This file is part of MyPet
*
* Copyright (C) 2011-2013 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet 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.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.gui.skillcreator;
import de.Keyle.MyPet.MyPetPlugin;
import de.Keyle.MyPet.gui.GuiMain;
import de.Keyle.MyPet.skill.MyPetSkillTree;
import de.Keyle.MyPet.skill.MyPetSkillTreeMobType;
import de.Keyle.MyPet.skill.skilltreeloader.MyPetSkillTreeLoaderJSON;
import de.Keyle.MyPet.skill.skilltreeloader.MyPetSkillTreeLoaderNBT;
import de.Keyle.MyPet.skill.skilltreeloader.MyPetSkillTreeLoaderYAML;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.event.*;
import java.io.File;
import java.util.List;
public class SkilltreeCreator
{
JComboBox mobTypeComboBox;
JButton addSkilltreeButton;
JButton deleteSkilltreeButton;
JTree skilltreeTree;
JButton skilltreeDownButton;
JButton skilltreeUpButton;
JPanel skilltreeCreatorPanel;
JButton saveButton;
JButton renameSkilltreeButton;
JFrame skilltreeCreatorFrame;
JPopupMenu saveButtonRightclickMenu;
JMenuItem asNBTMenuItem;
JMenuItem asJSONMenuItem;
JMenuItem asYAMLMenuItem;
JMenuItem asAllMenuItem;
JPopupMenu skilltreeListRightclickMenu;
JMenuItem copyMenuItem;
JMenuItem pasteMenuItem;
DefaultTreeModel skilltreeTreeModel;
private MyPetSkillTree skilltreeCopyPaste;
MyPetSkillTreeMobType selectedMobtype;
public SkilltreeCreator()
{
this.mobTypeComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
selectedMobtype = MyPetSkillTreeMobType.getMobTypeByName(mobTypeComboBox.getSelectedItem().toString());
skilltreeTreeSetSkilltrees();
}
}
});
skilltreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (skilltreeTree.getSelectionPath() != null && skilltreeTree.getSelectionPath().getPathCount() == 2)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
if (skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) <= 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
else if (selectedMobtype.getSkillTreePlace(skillTree) >= skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) - 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeDownButton.hasFocus())
{
skilltreeUpButton.requestFocus();
}
}
else if (selectedMobtype.getSkillTreePlace(skillTree) <= 0)
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(false);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeUpButton.hasFocus())
{
skilltreeDownButton.requestFocus();
}
}
else
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(true);
}
copyMenuItem.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
renameSkilltreeButton.setEnabled(true);
}
else
{
copyMenuItem.setEnabled(false);
deleteSkilltreeButton.setEnabled(false);
renameSkilltreeButton.setEnabled(false);
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
}
});
skilltreeUpButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeUp(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
skilltreeDownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeDown(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
addSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE);
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree skillTree = new MyPetSkillTree(response);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
}
});
renameSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
String response = (String) JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE, null, null, skillTree.getName());
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree newSkillTree = skillTree.clone(response);
selectedMobtype.removeSkillTree(skillTree.getName());
selectedMobtype.addSkillTree(newSkillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(newSkillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
skilltreeTreeSetSkilltrees();
}
}
}
});
deleteSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
}
}
}
});
skilltreeTree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
- if (evt.getClickCount() == 2)
+ if (evt.getClickCount() == 2 && skilltreeTree.getSelectionPath() != null)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
}
}
}
}
});
asAllMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asNBTMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asJSONMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asYAMLMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
saveButtonRightclickMenu.show(saveButton, 0, 0);
}
});
skilltreeTree.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
switch (e.getKeyCode())
{
case KeyEvent.VK_ENTER:
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
break;
case KeyEvent.VK_DELETE:
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
break;
}
}
}
}
});
copyMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
skilltreeCopyPaste = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
pasteMenuItem.setEnabled(true);
}
});
pasteMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
for (int i = 2 ; ; i++)
{
if (!selectedMobtype.hasSkillTree(skilltreeCopyPaste.getName() + "_" + i))
{
MyPetSkillTree skillTree = skilltreeCopyPaste.clone(skilltreeCopyPaste.getName() + "_" + i);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
break;
}
}
}
});
}
public JPanel getMainPanel()
{
return skilltreeCreatorPanel;
}
public JFrame getFrame()
{
if (skilltreeCreatorFrame == null)
{
skilltreeCreatorFrame = new JFrame("SkilltreeCreator - MyPet " + MyPetPlugin.MyPetVersion);
}
return skilltreeCreatorFrame;
}
public void selectSkilltree(String skilltreeName)
{
DefaultMutableTreeNode root = ((DefaultMutableTreeNode) skilltreeTreeModel.getRoot());
DefaultMutableTreeNode[] path = new DefaultMutableTreeNode[2];
path[0] = root;
for (int i = 0 ; i < root.getChildCount() ; i++)
{
if (root.getChildAt(i) instanceof SkillTreeNode)
{
SkillTreeNode node = (SkillTreeNode) root.getChildAt(i);
if (node.getSkillTree().getName().equals(skilltreeName))
{
path[1] = node;
TreePath treePath = new TreePath(path);
skilltreeTree.setSelectionPath(treePath);
return;
}
}
}
}
public void selectSkilltree(MyPetSkillTree skilltree)
{
DefaultMutableTreeNode root = ((DefaultMutableTreeNode) skilltreeTreeModel.getRoot());
DefaultMutableTreeNode[] path = new DefaultMutableTreeNode[2];
path[0] = root;
for (int i = 0 ; i < root.getChildCount() ; i++)
{
if (root.getChildAt(i) instanceof SkillTreeNode)
{
SkillTreeNode node = (SkillTreeNode) root.getChildAt(i);
if (node.getSkillTree() == skilltree)
{
path[1] = node;
TreePath treePath = new TreePath(path);
skilltreeTree.setSelectionPath(treePath);
return;
}
}
}
}
public void skilltreeTreeSetSkilltrees()
{
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(selectedMobtype.getMobTypeName());
skilltreeTreeModel.setRoot(rootNode);
for (MyPetSkillTree skillTree : selectedMobtype.getSkillTrees())
{
SkillTreeNode skillTreeNode = new SkillTreeNode(skillTree);
rootNode.add(skillTreeNode);
}
skilltreeTreeExpandAll();
}
public void skilltreeTreeExpandAll()
{
for (int i = 0 ; i < skilltreeTree.getRowCount() ; i++)
{
skilltreeTree.expandRow(i);
}
}
private void createUIComponents()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
skilltreeTreeModel = new DefaultTreeModel(root);
skilltreeTree = new JTree(skilltreeTreeModel);
skilltreeTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
createRightclickMenus();
selectedMobtype = MyPetSkillTreeMobType.getMobTypeByName("default");
skilltreeTreeSetSkilltrees();
}
public void createRightclickMenus()
{
skilltreeListRightclickMenu = new JPopupMenu();
copyMenuItem = new JMenuItem("Copy");
skilltreeListRightclickMenu.add(copyMenuItem);
pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.setEnabled(false);
skilltreeListRightclickMenu.add(pasteMenuItem);
MouseListener popupListener = new PopupListener(skilltreeListRightclickMenu);
skilltreeTree.addMouseListener(popupListener);
saveButtonRightclickMenu = new JPopupMenu();
asNBTMenuItem = new JMenuItem("NBT format (default)");
saveButtonRightclickMenu.add(asNBTMenuItem);
asJSONMenuItem = new JMenuItem("JSON format");
saveButtonRightclickMenu.add(asJSONMenuItem);
asYAMLMenuItem = new JMenuItem("YAML format");
saveButtonRightclickMenu.add(asYAMLMenuItem);
saveButtonRightclickMenu.addSeparator();
asAllMenuItem = new JMenuItem("All formats");
saveButtonRightclickMenu.add(asAllMenuItem);
}
private class SkillTreeNode extends DefaultMutableTreeNode
{
private MyPetSkillTree skillTree;
public SkillTreeNode(MyPetSkillTree skillTree)
{
super(skillTree.getName());
this.skillTree = skillTree;
}
public MyPetSkillTree getSkillTree()
{
return skillTree;
}
}
class PopupListener extends MouseAdapter
{
JPopupMenu popup;
PopupListener(JPopupMenu popupMenu)
{
popup = popupMenu;
}
public void mousePressed(MouseEvent e)
{
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e)
{
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e)
{
if (e.isPopupTrigger())
{
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
| true | true | public SkilltreeCreator()
{
this.mobTypeComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
selectedMobtype = MyPetSkillTreeMobType.getMobTypeByName(mobTypeComboBox.getSelectedItem().toString());
skilltreeTreeSetSkilltrees();
}
}
});
skilltreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (skilltreeTree.getSelectionPath() != null && skilltreeTree.getSelectionPath().getPathCount() == 2)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
if (skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) <= 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
else if (selectedMobtype.getSkillTreePlace(skillTree) >= skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) - 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeDownButton.hasFocus())
{
skilltreeUpButton.requestFocus();
}
}
else if (selectedMobtype.getSkillTreePlace(skillTree) <= 0)
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(false);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeUpButton.hasFocus())
{
skilltreeDownButton.requestFocus();
}
}
else
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(true);
}
copyMenuItem.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
renameSkilltreeButton.setEnabled(true);
}
else
{
copyMenuItem.setEnabled(false);
deleteSkilltreeButton.setEnabled(false);
renameSkilltreeButton.setEnabled(false);
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
}
});
skilltreeUpButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeUp(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
skilltreeDownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeDown(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
addSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE);
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree skillTree = new MyPetSkillTree(response);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
}
});
renameSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
String response = (String) JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE, null, null, skillTree.getName());
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree newSkillTree = skillTree.clone(response);
selectedMobtype.removeSkillTree(skillTree.getName());
selectedMobtype.addSkillTree(newSkillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(newSkillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
skilltreeTreeSetSkilltrees();
}
}
}
});
deleteSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
}
}
}
});
skilltreeTree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
}
}
}
}
});
asAllMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asNBTMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asJSONMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asYAMLMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
saveButtonRightclickMenu.show(saveButton, 0, 0);
}
});
skilltreeTree.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
switch (e.getKeyCode())
{
case KeyEvent.VK_ENTER:
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
break;
case KeyEvent.VK_DELETE:
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
break;
}
}
}
}
});
copyMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
skilltreeCopyPaste = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
pasteMenuItem.setEnabled(true);
}
});
pasteMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
for (int i = 2 ; ; i++)
{
if (!selectedMobtype.hasSkillTree(skilltreeCopyPaste.getName() + "_" + i))
{
MyPetSkillTree skillTree = skilltreeCopyPaste.clone(skilltreeCopyPaste.getName() + "_" + i);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
break;
}
}
}
});
}
| public SkilltreeCreator()
{
this.mobTypeComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
selectedMobtype = MyPetSkillTreeMobType.getMobTypeByName(mobTypeComboBox.getSelectedItem().toString());
skilltreeTreeSetSkilltrees();
}
}
});
skilltreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (skilltreeTree.getSelectionPath() != null && skilltreeTree.getSelectionPath().getPathCount() == 2)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
if (skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) <= 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
else if (selectedMobtype.getSkillTreePlace(skillTree) >= skilltreeTreeModel.getChildCount(skilltreeTreeModel.getRoot()) - 1)
{
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeDownButton.hasFocus())
{
skilltreeUpButton.requestFocus();
}
}
else if (selectedMobtype.getSkillTreePlace(skillTree) <= 0)
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(false);
deleteSkilltreeButton.setEnabled(true);
if (skilltreeUpButton.hasFocus())
{
skilltreeDownButton.requestFocus();
}
}
else
{
skilltreeDownButton.setEnabled(true);
skilltreeUpButton.setEnabled(true);
}
copyMenuItem.setEnabled(true);
deleteSkilltreeButton.setEnabled(true);
renameSkilltreeButton.setEnabled(true);
}
else
{
copyMenuItem.setEnabled(false);
deleteSkilltreeButton.setEnabled(false);
renameSkilltreeButton.setEnabled(false);
skilltreeDownButton.setEnabled(false);
skilltreeUpButton.setEnabled(false);
}
}
});
skilltreeUpButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeUp(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
skilltreeDownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.moveSkillTreeDown(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
}
}
});
addSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE);
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree skillTree = new MyPetSkillTree(response);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
}
});
renameSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
String response = (String) JOptionPane.showInputDialog(null, "Enter the name of the new skilltree.", "Create new Skilltree", JOptionPane.QUESTION_MESSAGE, null, null, skillTree.getName());
if (response != null)
{
if (response.matches("(?m)[\\w-]+"))
{
if (!selectedMobtype.hasSkillTree(response))
{
MyPetSkillTree newSkillTree = skillTree.clone(response);
selectedMobtype.removeSkillTree(skillTree.getName());
selectedMobtype.addSkillTree(newSkillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(newSkillTree);
}
else
{
JOptionPane.showMessageDialog(null, "There is already a skilltree with this name!", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "This is not a valid skilltree name!\n\na-z\nA-Z\n0-9\n_ -", "Create new Skilltree", JOptionPane.ERROR_MESSAGE);
}
}
skilltreeTreeSetSkilltrees();
}
}
}
});
deleteSkilltreeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
}
}
}
});
skilltreeTree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2 && skilltreeTree.getSelectionPath() != null)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
}
}
}
}
});
asAllMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asNBTMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderNBT.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".st";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asJSONMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderJSON.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".json";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
asYAMLMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String savedPetsString = "";
List<String> savedPetTypes;
savedPetTypes = MyPetSkillTreeLoaderYAML.getSkilltreeLoader().saveSkillTrees(GuiMain.configPath + "skilltrees");
for (String petType : savedPetTypes)
{
savedPetsString += "\n " + petType.toLowerCase() + ".yml";
}
JOptionPane.showMessageDialog(null, "Saved to:\n" + GuiMain.configPath + "skilltrees" + File.separator + savedPetsString, "Saved following configs", JOptionPane.INFORMATION_MESSAGE);
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
saveButtonRightclickMenu.show(saveButton, 0, 0);
}
});
skilltreeTree.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (skilltreeTree.getSelectionPath().getPath().length == 2)
{
if (skilltreeTree.getSelectionPath().getPathComponent(1) instanceof SkillTreeNode)
{
MyPetSkillTree skillTree = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
switch (e.getKeyCode())
{
case KeyEvent.VK_ENTER:
GuiMain.levelCreator.setSkillTree(skillTree, selectedMobtype);
GuiMain.levelCreator.getFrame().setVisible(true);
skilltreeCreatorFrame.setEnabled(false);
break;
case KeyEvent.VK_DELETE:
selectedMobtype.removeSkillTree(skillTree.getName());
skilltreeTreeSetSkilltrees();
break;
}
}
}
}
});
copyMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
skilltreeCopyPaste = ((SkillTreeNode) skilltreeTree.getSelectionPath().getPathComponent(1)).getSkillTree();
pasteMenuItem.setEnabled(true);
}
});
pasteMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
for (int i = 2 ; ; i++)
{
if (!selectedMobtype.hasSkillTree(skilltreeCopyPaste.getName() + "_" + i))
{
MyPetSkillTree skillTree = skilltreeCopyPaste.clone(skilltreeCopyPaste.getName() + "_" + i);
selectedMobtype.addSkillTree(skillTree);
skilltreeTreeSetSkilltrees();
selectSkilltree(skillTree);
break;
}
}
}
});
}
|
diff --git a/org.eclipse.ua.tests/intro/org/eclipse/ua/tests/intro/contentdetect/ContentDetectorTest.java b/org.eclipse.ua.tests/intro/org/eclipse/ua/tests/intro/contentdetect/ContentDetectorTest.java
index c9c783fc7..47e5cf7e2 100644
--- a/org.eclipse.ua.tests/intro/org/eclipse/ua/tests/intro/contentdetect/ContentDetectorTest.java
+++ b/org.eclipse.ua.tests/intro/org/eclipse/ua/tests/intro/contentdetect/ContentDetectorTest.java
@@ -1,151 +1,150 @@
/*******************************************************************************
* Copyright (c) 2007 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.ua.tests.intro.contentdetect;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.eclipse.ui.internal.intro.impl.model.ExtensionMap;
import org.eclipse.ui.internal.intro.universal.contentdetect.ContentDetectHelper;
import org.eclipse.ui.internal.intro.universal.contentdetect.ContentDetector;
public class ContentDetectorTest extends TestCase {
public void testContributorCount() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.saveExtensionCount(4);
assertEquals(4, helper.getExtensionCount());
assertEquals(4, helper.getExtensionCount());
helper.saveExtensionCount(5);
helper.saveExtensionCount(6);
assertEquals(6, helper.getExtensionCount());
}
public void testContributorSaveNoNames() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.saveContributors(new HashSet());
assertTrue(helper.getContributors().size() == 0);
}
public void testContributorSaveThreeContributors() {
ContentDetectHelper helper = new ContentDetectHelper();
HashSet contributors = new HashSet();
contributors.add("one");
contributors.add("two");
contributors.add("three");
helper.saveContributors(contributors);
Set savedContributors = helper.getContributors();
assertTrue(savedContributors.size() == 3);
assertTrue(savedContributors.contains("one"));
assertTrue(savedContributors.contains("two"));
assertTrue(savedContributors.contains("three"));
}
public void testForNewContent() {
ContentDetectHelper helper = new ContentDetectHelper();
HashSet contributors = new HashSet();
contributors.add("one");
contributors.add("two");
contributors.add("three");
contributors.add("four");
Set previous = new HashSet();
previous.add("five");
previous.add("two");
previous.add("one");
Set newContributors = helper.findNewContributors(contributors, previous);
assertTrue(newContributors.size() == 2);
assertTrue(newContributors.contains("four"));
assertTrue(newContributors.contains("three"));
}
public void testNoSavedState() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.deleteStateFiles();
assertTrue(helper.getContributors().isEmpty());
assertEquals(ContentDetectHelper.NO_STATE, helper.getExtensionCount());
ContentDetector detector = new ContentDetector();
assertFalse(detector.isNewContentAvailable());
Set newContent = ContentDetector.getNewContributors();
assertTrue(newContent == null || newContent.size() == 0);
String firstContribution = (String) helper.getContributors().iterator().next();
assertFalse(ContentDetector.isNew(firstContribution));
}
public void testStateChanges() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.deleteStateFiles();
ContentDetector detector = new ContentDetector();
assertFalse(detector.isNewContentAvailable());
// Calling the detector should save the state
int extensionCount = helper.getExtensionCount();
assertTrue(extensionCount > 0);
// Simulate removing an extension
helper.saveExtensionCount(extensionCount + 1);
assertFalse(detector.isNewContentAvailable());
// Make the first extension appear new
helper.saveExtensionCount(extensionCount - 1);
- assertEquals(extensionCount, helper.getContributors().size());
Set contributors = helper.getContributors();
String firstContribution = (String) contributors.iterator().next();
String copyOfFirstContribution = "" + firstContribution;
contributors.remove(firstContribution);
helper.saveContributors(contributors);
assertTrue(detector.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
// Calling a new detector should yield the same result
ContentDetector detector2 = new ContentDetector();
assertTrue(detector2.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
}
public void testExtensionMapSingleton() {
ExtensionMap map1 = ExtensionMap.getInstance();
ExtensionMap map2 = ExtensionMap.getInstance();
assertEquals(map1, map2);
}
public void testExtensionMapping() {
ExtensionMap map = ExtensionMap.getInstance();
map.clear();
map.putPluginId("anchor1", "org.eclipse.test");
map.putPluginId("anchor2", "org.eclipse.test");
map.putPluginId("anchor3", "org.eclipse.test3");
assertEquals("org.eclipse.test", map.getPluginId("anchor1"));
assertEquals("org.eclipse.test", map.getPluginId("anchor2"));
assertEquals("org.eclipse.test3", map.getPluginId("anchor3"));
map.clear();
assertNull(map.getPluginId("anchor1"));
}
public void testStartPage() {
ExtensionMap map = ExtensionMap.getInstance();
map.setStartPage("tutorials");
map.setStartPage("whats-new");
assertEquals("whats-new", map.getStartPage());
map.clear();
assertNull(map.getStartPage());
}
protected void finalize() throws Throwable {
// Delete state files so that if we start Eclipse we don't see all content as new
ContentDetectHelper helper = new ContentDetectHelper();
helper.deleteStateFiles();
super.finalize();
}
}
| true | true | public void testStateChanges() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.deleteStateFiles();
ContentDetector detector = new ContentDetector();
assertFalse(detector.isNewContentAvailable());
// Calling the detector should save the state
int extensionCount = helper.getExtensionCount();
assertTrue(extensionCount > 0);
// Simulate removing an extension
helper.saveExtensionCount(extensionCount + 1);
assertFalse(detector.isNewContentAvailable());
// Make the first extension appear new
helper.saveExtensionCount(extensionCount - 1);
assertEquals(extensionCount, helper.getContributors().size());
Set contributors = helper.getContributors();
String firstContribution = (String) contributors.iterator().next();
String copyOfFirstContribution = "" + firstContribution;
contributors.remove(firstContribution);
helper.saveContributors(contributors);
assertTrue(detector.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
// Calling a new detector should yield the same result
ContentDetector detector2 = new ContentDetector();
assertTrue(detector2.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
}
| public void testStateChanges() {
ContentDetectHelper helper = new ContentDetectHelper();
helper.deleteStateFiles();
ContentDetector detector = new ContentDetector();
assertFalse(detector.isNewContentAvailable());
// Calling the detector should save the state
int extensionCount = helper.getExtensionCount();
assertTrue(extensionCount > 0);
// Simulate removing an extension
helper.saveExtensionCount(extensionCount + 1);
assertFalse(detector.isNewContentAvailable());
// Make the first extension appear new
helper.saveExtensionCount(extensionCount - 1);
Set contributors = helper.getContributors();
String firstContribution = (String) contributors.iterator().next();
String copyOfFirstContribution = "" + firstContribution;
contributors.remove(firstContribution);
helper.saveContributors(contributors);
assertTrue(detector.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
// Calling a new detector should yield the same result
ContentDetector detector2 = new ContentDetector();
assertTrue(detector2.isNewContentAvailable());
assertEquals(1, ContentDetector.getNewContributors().size());
assertTrue(ContentDetector.isNew(firstContribution));
assertTrue(ContentDetector.isNew(copyOfFirstContribution));
}
|
diff --git a/src/xmlhandle/Xmlhandle.java b/src/xmlhandle/Xmlhandle.java
index 14b32d7..2309cc6 100644
--- a/src/xmlhandle/Xmlhandle.java
+++ b/src/xmlhandle/Xmlhandle.java
@@ -1,536 +1,536 @@
package xmlhandle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import connection.Client;
import dbhandle.Event;
import dbhandle.MessageAction;
import dbhandle.Status;
import dbhandle.User;
public class Xmlhandle {
private ActionListener listener;
private String msg;
private String username;
public static Document stringToXML(String string) throws DocumentException {
return DocumentHelper.parseText(string);
}
//Receiver methods
public void performMessageInstructions(Document xml) throws NumberFormatException, ParseException, SQLException{
//Implement appropriate responses
Element root = xml.getRootElement();
String ownerUsername = null;
Element ownerElement = root.element("owner");
if (ownerElement != null) {
ownerUsername = ownerElement.attributeValue("owner_username");
}
Xmlaction actionToPerform = new Xmlaction(ownerUsername);
MessageAction action = MessageAction.valueOf(root.getName());
if (action == MessageAction.LOGIN) {
//Respond by sending back all the information the logged in user would need
Element loginCandidate = root.element("login_attempt");
String password = loginCandidate.attributeValue("password");
Document document = actionToPerform.login(ownerUsername, password);
serverSend(document.asXML(), ownerUsername);
} else if (action == MessageAction.CREATE_MEETING) {
List<Integer> userIDList; Event newEvent; int meetingRoomID = -1; String meetingName;
//Finds all User objects
userIDList = XMLtoUserIDList(root);
//Finds the event it needs
newEvent = XMLtoEvent(root);
//Finds the meeting name
Element meetingElement = root.element("meeting");
meetingName = meetingElement.attributeValue("meeting_name");
//Does the meeting have a booked room? -- Returns null if not found
Element meetingRoomElement = root.element("meeting_room");
if(!(meetingRoomElement == null)) {
meetingRoomID = Integer.valueOf(meetingRoomElement.attributeValue("meeting_room_ID"));
}
//Perform the action
Document document = actionToPerform.createMeeting(userIDList, newEvent, meetingRoomID, meetingName);
//Send the message to the appropriate users!
changeNotificationBroadcast(actionToPerform.getBroadcastTo(), document.asXML());
} else if (action == MessageAction.EDIT_MEETING) {
//TODO
Event eventChanges; int meetingID;
eventChanges = XMLtoEvent(root);
Element meetingElement = root.element("meeting");
meetingID = Integer.valueOf(meetingElement.attributeValue("meeting_ID"));
actionToPerform.editMeeting(eventChanges, meetingID);
} else if (action == MessageAction.CREATE_USER) {
//Probably not gonna be used in the "final" product
User newUser = XMLtoUser(root);
actionToPerform.createUser(newUser);
} else if (action == MessageAction.EDIT_NAME_OF_USER) {
Element changeName = root.element("change_name");
String newName = changeName.attributeValue("new_name");
Document document = actionToPerform.editNameOfUser(newName);
serverBroadcast(document.asXML());
} else if (action == MessageAction.EDIT_USER_PASSWORD) {
Element changePassword = root.element("change_password");
String oldPassword = changePassword.attributeValue("old_password");
String newPassword = changePassword.attributeValue("new_password");
Document document = actionToPerform.editUserPassword(oldPassword, newPassword);
serverSend(document.asXML(), ownerUsername);
} else if (action == MessageAction.EDIT_EVENT) {
Event eventToEdit = XMLtoEvent(root);
actionToPerform.editEvent(eventToEdit);
} else if (action == MessageAction.FETCH) {
//What needs to be in here?
}
}
//This will be run from the client to interpret incoming messages
public void interpretMessageData(Document xml, Client client) throws ParseException {
//This can be
Element root = xml.getRootElement();
String ownerUsername = null;
int ownerID;
String ownerName = null;
Element ownerElement = root.element("owner");
ownerUsername = ownerElement.attributeValue("owner_username");
ownerID = Integer.valueOf(ownerElement.attributeValue("owner_ID"));
ownerName = ownerElement.attributeValue("owner_name");
MessageAction action = MessageAction.valueOf(root.getName());
if (action == MessageAction.LOGIN) {
if (root.element("login_response").attributeValue("response").equals("Failure")) {
System.out.println("Wrong password or username");
return;
}
//Create the logged in user's object
Models.User loginUser = new Models.User(ownerID, ownerUsername);
loginUser.setName(ownerName);
//Iterates through all the personal events
List<Models.Event> eventList = new ArrayList<Models.Event>();
for ( Iterator i = root.elementIterator( "personal_event" ); i.hasNext(); ) {
Element eventElement = (Element) i.next();
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, loginUser, title, start, end, location, description);
event.setStatus(status);
eventList.add(event);
}
//Iterates through all the followed users
List<Models.User> followedUserList = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "followed_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User followedUser = new Models.User(userID, username);
followedUser.setName(name);
followedUserList.add(followedUser);
List<Models.Event> followedUserEventList = new ArrayList<Models.Event>();
//And iterates through their events
for ( Iterator y = root.elementIterator( "followed_user_event" ); y.hasNext(); ) {
Element eventElement = (Element) y.next();
if (eventElement.attributeValue("event_owner").equalsIgnoreCase(username)) {
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, followedUser, title, start, end, location, description);
event.setStatus(status);
followedUserEventList.add(event);
followedUser.setEvents((ArrayList<Models.Event>) followedUserEventList);
}
}
}
//Adds all the users in the database
List<Models.User> allUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "database_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User user = new Models.User(userID, username);
user.setName(name);
allUsers.add(user);
}
//TODO Group them up in meetings
client.setUser(loginUser);
- client.setMyUsers((ArrayList<Models.User>) followedUserList);
+ client.getUser().setImportedCalendars(((ArrayList<Models.User>) followedUserList));
client.setAllUsers((ArrayList<Models.User>)allUsers);
} else if (action == MessageAction.CREATE_MEETING) {
//Create the meeting leader
Models.User meetingLeader = new Models.User(ownerID, ownerUsername);
meetingLeader.setName(ownerName);
Element meetingElement = root.element("meeting");
int meetingID = Integer.valueOf(meetingElement.attributeValue("meeting_ID"));
String meetingName = meetingElement.attributeValue("name");
//Find the invited users of the meeting
List<Models.User> invitedUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "participant" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
for (Models.User user : client.getAllUsers()) {
if (userID == user.getUSER_ID()) {
invitedUsers.add(user);
}
}
}
//Find the meeting leaders event
Element eventElement = root.element("leader_event");
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
Models.Event event = new Models.Event(eventID, meetingLeader, meetingName, start, end, location, description);
Models.Meeting createdMeeting = new Models.Meeting(event);
createdMeeting.setMeetingID(meetingID);
createdMeeting.setParticipants((ArrayList<Models.User>) invitedUsers);
client.getMeetings().add(createdMeeting);
} else if (action == MessageAction.CREATE_USER) {
} else if (action == MessageAction.EDIT_NAME_OF_USER) {
} else if (action == MessageAction.EDIT_USER_PASSWORD) {
} else if (action == MessageAction.EDIT_EVENT) {
}
}
//Sender methods
public void createLoginRequest(String username, String password) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.LOGIN.toString());
root.addElement("owner")
.addAttribute("owner_username",username);
root.addElement("login_attempt")
.addAttribute("password", password);
clientSend(document.asXML());
}
//This will run on the client side. This can probably user the User class? -- tested and should be working
public void createAddMeetingRequest(List<Integer> userList, Event event, int meetingRoomID, String meetingName, String requestedBy) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.CREATE_MEETING.toString());
//Adds the username of the owner
root.addElement("owner")
.addAttribute("owner_username",requestedBy);
//The users to be added
for (int userID : userList) {
root.addElement("user")
.addAttribute("user_ID", String.valueOf(userID));
}
root.addElement("meeting")
.addAttribute("meeting_name", meetingName);
//The event that will be created for all the users
//TODO: Fix the problem with the dates
root.addElement("event")
.addAttribute("start", event.getStart().toString())
.addAttribute("end", event.getEnd().toString())
.addAttribute("location", event.getLocation())
.addAttribute("description",event.getDescription())
.addAttribute("status",event.getStatus().toString());
//Adds the meeting room
if (meetingRoomID != -1) {
root.addElement("meeting_room")
.addAttribute("meeting_room_ID",String.valueOf(meetingRoomID));
}
clientSend(document.asXML());
}
//TODO: Change it to only include the changes?
public void createEditMeetingRequest(Event eventChanges, int meetingID, String requestedBy) {
//Here eventChanges includes the original events ID aswell as all the changes
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.EDIT_MEETING.toString());
//Adds the username of the owner
root.addElement("owner")
.addAttribute("owner_username", requestedBy);
root.addElement("event")
.addAttribute("event_ID", String.valueOf(eventChanges.getEvent_ID()))
.addAttribute("start", eventChanges.getStart().toString())
.addAttribute("end", eventChanges.getEnd().toString())
.addAttribute("location", eventChanges.getLocation())
.addAttribute("description",eventChanges.getDescription())
.addAttribute("status",eventChanges.getStatus().toString());
root.addElement("meeting")
.addAttribute("meeting_ID", String.valueOf(meetingID));
clientSend(document.asXML());
}
public void createAddUserRequest(User newUser, String requestedBy) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.CREATE_USER.toString());
//Adds the username of the owner
root.addElement("owner")
.addAttribute("owner_username",requestedBy);
root.addElement("user")
.addAttribute("username", newUser.getUsername())
.addAttribute("password", newUser.getPassword())
.addAttribute("name", newUser.getName());
clientSend(document.asXML());
}
public void createEditNameOfUserRequest(String newName, String requestedBy) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.EDIT_NAME_OF_USER.toString());
//Adds the username of the owner
root.addElement("owner")
.addAttribute("owner_username",requestedBy);
root.addElement("change_name")
.addAttribute("new_name", newName);
clientSend(document.asXML());
}
public void createEditUserPasswordRequest(String oldPassword, String newPassword, String requestedBy) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.EDIT_USER_PASSWORD.toString());
root.addElement("owner")
.addAttribute("owner_username", requestedBy);
root.addElement("change_password")
.addAttribute("old_password", oldPassword)
.addAttribute("new_password", newPassword);
clientSend(document.asXML());
}
public void createEditEventRequest(Event eventChanges, String requestedBy) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(MessageAction.EDIT_EVENT.toString());
//Adds the user_ID and the username of the owner
root.addElement("owner")
.addAttribute("owner_username",requestedBy);
root.addElement("event")
.addAttribute("event_ID", String.valueOf(eventChanges.getEvent_ID()))
.addAttribute("start", eventChanges.getStart().toString())
.addAttribute("end", eventChanges.getEnd().toString())
.addAttribute("location", eventChanges.getLocation())
.addAttribute("description",eventChanges.getDescription())
.addAttribute("status",eventChanges.getStatus().toString());
clientSend(document.asXML());
}
//Fetch requests
public Document fetchUser(String username, String requestedBy) {
return null;
}
//Helper methods
private Timestamp StringToDate(String string) throws ParseException {
Timestamp timestamp = Timestamp.valueOf(string);
return timestamp;
}
private Event XMLtoEvent(Element root) throws NumberFormatException, ParseException {
Element eventElement = root.element("event");
int userID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
return new Event(userID,start,end,location,description,status);
}
private User XMLtoUser(Element root) {
Element userElement = root.element("user");
String username = userElement.attributeValue("username");
String password = userElement.attributeValue("password");
String name = userElement.attributeValue("name");
return new User(username,password,name);
}
private List<Integer> XMLtoUserIDList(Element root) {
List<Integer> userIDList = new ArrayList<Integer>();
for ( Iterator i = root.elementIterator( "user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
String user_ID = userElement.attributeValue("user_ID");
userIDList.add(Integer.valueOf(user_ID));
}
return userIDList;
}
private List<User> XMLtoUserList(Element root) {
List<User> userList = new ArrayList<User>();
for ( Iterator i = root.elementIterator( "user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
String user_ID = userElement.attributeValue("user_ID");
String username = userElement.attributeValue("username");
String password = userElement.attributeValue("password");
String name = userElement.attributeValue("name");
User user = new User(Integer.valueOf(user_ID),username,password,name);
userList.add(user);
}
return userList;
}
public static String extractUsername(String xml) throws DocumentException {
Document document = stringToXML(xml);
Element root = document.getRootElement();
Element owner = root.element("owner");
return owner.attributeValue("owner_username");
}
public void addListener(ActionListener listener) {
this.listener = listener;
}
//Use this in another method to send to all related users
private void serverSend(String msg, String username) {
this.msg = msg;
this.username = username;
listener.actionPerformed(new ActionEvent(this, 0, "sendingmsg"));
}
//Might not be used
private void serverBroadcast(String msg) {
this.msg = msg;
this.username = null;
listener.actionPerformed(new ActionEvent(this, 0, "sendingmsg"));
}
private void clientSend(String msg) {
this.msg = msg;
listener.actionPerformed(new ActionEvent(this, 0, "sendingmsg"));
}
private void changeNotificationBroadcast(List<User> broadcastTo, String msg) {
for (User user : broadcastTo) {
serverSend(msg, user.getUsername());
}
}
public static String extractMessageAction(String xml) throws DocumentException {
Document document = stringToXML(xml);
Element root = document.getRootElement();
return root.getName();
}
public String getUsernameForSending() {
return username;
}
public String getMsgForSending() {
return msg;
}
}
| true | true | public void interpretMessageData(Document xml, Client client) throws ParseException {
//This can be
Element root = xml.getRootElement();
String ownerUsername = null;
int ownerID;
String ownerName = null;
Element ownerElement = root.element("owner");
ownerUsername = ownerElement.attributeValue("owner_username");
ownerID = Integer.valueOf(ownerElement.attributeValue("owner_ID"));
ownerName = ownerElement.attributeValue("owner_name");
MessageAction action = MessageAction.valueOf(root.getName());
if (action == MessageAction.LOGIN) {
if (root.element("login_response").attributeValue("response").equals("Failure")) {
System.out.println("Wrong password or username");
return;
}
//Create the logged in user's object
Models.User loginUser = new Models.User(ownerID, ownerUsername);
loginUser.setName(ownerName);
//Iterates through all the personal events
List<Models.Event> eventList = new ArrayList<Models.Event>();
for ( Iterator i = root.elementIterator( "personal_event" ); i.hasNext(); ) {
Element eventElement = (Element) i.next();
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, loginUser, title, start, end, location, description);
event.setStatus(status);
eventList.add(event);
}
//Iterates through all the followed users
List<Models.User> followedUserList = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "followed_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User followedUser = new Models.User(userID, username);
followedUser.setName(name);
followedUserList.add(followedUser);
List<Models.Event> followedUserEventList = new ArrayList<Models.Event>();
//And iterates through their events
for ( Iterator y = root.elementIterator( "followed_user_event" ); y.hasNext(); ) {
Element eventElement = (Element) y.next();
if (eventElement.attributeValue("event_owner").equalsIgnoreCase(username)) {
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, followedUser, title, start, end, location, description);
event.setStatus(status);
followedUserEventList.add(event);
followedUser.setEvents((ArrayList<Models.Event>) followedUserEventList);
}
}
}
//Adds all the users in the database
List<Models.User> allUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "database_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User user = new Models.User(userID, username);
user.setName(name);
allUsers.add(user);
}
//TODO Group them up in meetings
client.setUser(loginUser);
client.setMyUsers((ArrayList<Models.User>) followedUserList);
client.setAllUsers((ArrayList<Models.User>)allUsers);
} else if (action == MessageAction.CREATE_MEETING) {
//Create the meeting leader
Models.User meetingLeader = new Models.User(ownerID, ownerUsername);
meetingLeader.setName(ownerName);
Element meetingElement = root.element("meeting");
int meetingID = Integer.valueOf(meetingElement.attributeValue("meeting_ID"));
String meetingName = meetingElement.attributeValue("name");
//Find the invited users of the meeting
List<Models.User> invitedUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "participant" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
for (Models.User user : client.getAllUsers()) {
if (userID == user.getUSER_ID()) {
invitedUsers.add(user);
}
}
}
//Find the meeting leaders event
Element eventElement = root.element("leader_event");
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
Models.Event event = new Models.Event(eventID, meetingLeader, meetingName, start, end, location, description);
Models.Meeting createdMeeting = new Models.Meeting(event);
createdMeeting.setMeetingID(meetingID);
createdMeeting.setParticipants((ArrayList<Models.User>) invitedUsers);
client.getMeetings().add(createdMeeting);
} else if (action == MessageAction.CREATE_USER) {
} else if (action == MessageAction.EDIT_NAME_OF_USER) {
} else if (action == MessageAction.EDIT_USER_PASSWORD) {
} else if (action == MessageAction.EDIT_EVENT) {
}
}
| public void interpretMessageData(Document xml, Client client) throws ParseException {
//This can be
Element root = xml.getRootElement();
String ownerUsername = null;
int ownerID;
String ownerName = null;
Element ownerElement = root.element("owner");
ownerUsername = ownerElement.attributeValue("owner_username");
ownerID = Integer.valueOf(ownerElement.attributeValue("owner_ID"));
ownerName = ownerElement.attributeValue("owner_name");
MessageAction action = MessageAction.valueOf(root.getName());
if (action == MessageAction.LOGIN) {
if (root.element("login_response").attributeValue("response").equals("Failure")) {
System.out.println("Wrong password or username");
return;
}
//Create the logged in user's object
Models.User loginUser = new Models.User(ownerID, ownerUsername);
loginUser.setName(ownerName);
//Iterates through all the personal events
List<Models.Event> eventList = new ArrayList<Models.Event>();
for ( Iterator i = root.elementIterator( "personal_event" ); i.hasNext(); ) {
Element eventElement = (Element) i.next();
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, loginUser, title, start, end, location, description);
event.setStatus(status);
eventList.add(event);
}
//Iterates through all the followed users
List<Models.User> followedUserList = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "followed_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User followedUser = new Models.User(userID, username);
followedUser.setName(name);
followedUserList.add(followedUser);
List<Models.Event> followedUserEventList = new ArrayList<Models.Event>();
//And iterates through their events
for ( Iterator y = root.elementIterator( "followed_user_event" ); y.hasNext(); ) {
Element eventElement = (Element) y.next();
if (eventElement.attributeValue("event_owner").equalsIgnoreCase(username)) {
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
int meetingID = Integer.valueOf(eventElement.attributeValue("meetingID"));
String title = eventElement.attributeValue("meetingName");
Models.Event event = new Models.Event(eventID, followedUser, title, start, end, location, description);
event.setStatus(status);
followedUserEventList.add(event);
followedUser.setEvents((ArrayList<Models.Event>) followedUserEventList);
}
}
}
//Adds all the users in the database
List<Models.User> allUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "database_user" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
String username = userElement.attributeValue("username");
String name = userElement.attributeValue("name");
Models.User user = new Models.User(userID, username);
user.setName(name);
allUsers.add(user);
}
//TODO Group them up in meetings
client.setUser(loginUser);
client.getUser().setImportedCalendars(((ArrayList<Models.User>) followedUserList));
client.setAllUsers((ArrayList<Models.User>)allUsers);
} else if (action == MessageAction.CREATE_MEETING) {
//Create the meeting leader
Models.User meetingLeader = new Models.User(ownerID, ownerUsername);
meetingLeader.setName(ownerName);
Element meetingElement = root.element("meeting");
int meetingID = Integer.valueOf(meetingElement.attributeValue("meeting_ID"));
String meetingName = meetingElement.attributeValue("name");
//Find the invited users of the meeting
List<Models.User> invitedUsers = new ArrayList<Models.User>();
for ( Iterator i = root.elementIterator( "participant" ); i.hasNext(); ) {
Element userElement = (Element) i.next();
int userID = Integer.valueOf(userElement.attributeValue("user_ID"));
for (Models.User user : client.getAllUsers()) {
if (userID == user.getUSER_ID()) {
invitedUsers.add(user);
}
}
}
//Find the meeting leaders event
Element eventElement = root.element("leader_event");
int eventID = Integer.valueOf(eventElement.attributeValue("event_ID"));
Timestamp start = StringToDate(eventElement.attributeValue("start"));
Timestamp end = StringToDate(eventElement.attributeValue("end"));
String location = eventElement.attributeValue("location");
String description = eventElement.attributeValue("description");
Status status = Status.valueOf(eventElement.attributeValue("status"));
Models.Event event = new Models.Event(eventID, meetingLeader, meetingName, start, end, location, description);
Models.Meeting createdMeeting = new Models.Meeting(event);
createdMeeting.setMeetingID(meetingID);
createdMeeting.setParticipants((ArrayList<Models.User>) invitedUsers);
client.getMeetings().add(createdMeeting);
} else if (action == MessageAction.CREATE_USER) {
} else if (action == MessageAction.EDIT_NAME_OF_USER) {
} else if (action == MessageAction.EDIT_USER_PASSWORD) {
} else if (action == MessageAction.EDIT_EVENT) {
}
}
|
diff --git a/src/test/cases/Main.java b/src/test/cases/Main.java
index fac69bd..c56eccd 100644
--- a/src/test/cases/Main.java
+++ b/src/test/cases/Main.java
@@ -1,127 +1,127 @@
package test.cases;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.zkoss.zul.Hbox;
import test.util.XMLConverter;
public class Main {
private static int count = 0;
private static final List<String> comps = Arrays.asList(new String[] {
"Div", "Panel", "Window", "Groupbox", "Tabbox", "Hlayout", "Hbox",
"Vlayout", "Vbox" });
private static final List<String> inps = Arrays.asList(new String[] {
"Bandbox", "Calendar", "Chosenbox", "Colorbox", "Combobox",
"Datebox", "Decimalbox", "Doublebox", "Intbox", "Longbox",
"Textbox", "Timebox", "Doublespinner", "Spinner", "Slider" });
public static void main(String[] args) throws Exception {
for (String comp : comps) {
outputCase(new VFlexCase(comp, false));
outputCase(new LayoutCase(comp, "Hlayout", false),
new LayoutCase(comp, "Hbox", false));
outputCase(new LayoutCase(comp, "Vlayout", false),
new LayoutCase(comp, "Vbox", false));
outputCase(new MinFlexCase(comp, "Hlayout", false),
new MinFlexCase(comp, "Hbox", false));
outputCase(new MinFlexCase(comp, "Vlayout", false),
new MinFlexCase(comp, "Vbox", false));
}
for (String inp : inps) {
outputCase(new VFlexCase(inp, true), new VFlexCase(inp, false));
outputCase(new LayoutCase(inp, "Hlayout", false),
new LayoutCase(inp, "Hbox", false),
new LayoutCase(inp, "Hlayout", true),
new LayoutCase(inp, "Hbox", true));
outputCase(new LayoutCase(inp, "Vlayout", false),
new LayoutCase(inp, "Vbox", false),
new LayoutCase(inp, "Vlayout", true),
new LayoutCase(inp, "Vbox", true));
outputCase(new MinFlexCase(inp, "Hlayout", false),
new MinFlexCase(inp, "Hbox", false),
- new MinFlexCase(inp, "Vlayout", true),
- new MinFlexCase(inp, "Vbox", true));
- outputCase(new MinFlexCase(inp, "Hlayout", false),
- new MinFlexCase(inp, "Hbox", false),
+ new MinFlexCase(inp, "Hlayout", true),
+ new MinFlexCase(inp, "Hbox", true));
+ outputCase(new MinFlexCase(inp, "Vlayout", false),
+ new MinFlexCase(inp, "Vbox", false),
new MinFlexCase(inp, "Vlayout", true),
new MinFlexCase(inp, "Vbox", true));
outputCase(new InputHFlexCase(inp, false),
new InputHFlexCase(inp, true));
}
}
private static void save(String content, File file) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
fileWriter.write(content);
} catch (IOException ex) {
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static File generateZTL() throws IOException {
String path = new StringBuffer("WebContent/Z65-Flex-")
.append(String.format("%03d", ++count)).append(".zul")
.toString();
File tmp = new File(path);
tmp.createNewFile();
return tmp;
}
private static void outputCase(FlexCase... flexCases) throws Exception {
StringBuffer flexCaseXML = new StringBuffer("<zk>");
Hbox hbox1 = new Hbox();
Hbox hbox2 = new Hbox();
for (int i = 0; i < flexCases.length; i++) {
FlexCase flexCase = flexCases[i];
switch (flexCases.length) {
case 1:
flexCaseXML.append(flexCase.getViewXML());
break;
case 2:
hbox1.appendChild(flexCase.getView());
if (i == 1)
flexCaseXML.append(new XMLConverter(hbox1).toXML());
break;
case 4:
if (i < 2)
hbox1.appendChild(flexCase.getView());
else if (i > 1)
hbox2.appendChild(flexCase.getView());
if (i == 1)
flexCaseXML.append(new XMLConverter(hbox1).toXML());
if (i == 3)
flexCaseXML.append(new XMLConverter(hbox2).toXML());
break;
}
}
flexCaseXML.append("</zk>");
File ztl = generateZTL();
save(flexCaseXML.toString(), ztl);
System.out.println("save to file " + ztl.getName());
System.out.println("file contnet: \n" + flexCaseXML + "\n");
}
}
| true | true | public static void main(String[] args) throws Exception {
for (String comp : comps) {
outputCase(new VFlexCase(comp, false));
outputCase(new LayoutCase(comp, "Hlayout", false),
new LayoutCase(comp, "Hbox", false));
outputCase(new LayoutCase(comp, "Vlayout", false),
new LayoutCase(comp, "Vbox", false));
outputCase(new MinFlexCase(comp, "Hlayout", false),
new MinFlexCase(comp, "Hbox", false));
outputCase(new MinFlexCase(comp, "Vlayout", false),
new MinFlexCase(comp, "Vbox", false));
}
for (String inp : inps) {
outputCase(new VFlexCase(inp, true), new VFlexCase(inp, false));
outputCase(new LayoutCase(inp, "Hlayout", false),
new LayoutCase(inp, "Hbox", false),
new LayoutCase(inp, "Hlayout", true),
new LayoutCase(inp, "Hbox", true));
outputCase(new LayoutCase(inp, "Vlayout", false),
new LayoutCase(inp, "Vbox", false),
new LayoutCase(inp, "Vlayout", true),
new LayoutCase(inp, "Vbox", true));
outputCase(new MinFlexCase(inp, "Hlayout", false),
new MinFlexCase(inp, "Hbox", false),
new MinFlexCase(inp, "Vlayout", true),
new MinFlexCase(inp, "Vbox", true));
outputCase(new MinFlexCase(inp, "Hlayout", false),
new MinFlexCase(inp, "Hbox", false),
new MinFlexCase(inp, "Vlayout", true),
new MinFlexCase(inp, "Vbox", true));
outputCase(new InputHFlexCase(inp, false),
new InputHFlexCase(inp, true));
}
}
| public static void main(String[] args) throws Exception {
for (String comp : comps) {
outputCase(new VFlexCase(comp, false));
outputCase(new LayoutCase(comp, "Hlayout", false),
new LayoutCase(comp, "Hbox", false));
outputCase(new LayoutCase(comp, "Vlayout", false),
new LayoutCase(comp, "Vbox", false));
outputCase(new MinFlexCase(comp, "Hlayout", false),
new MinFlexCase(comp, "Hbox", false));
outputCase(new MinFlexCase(comp, "Vlayout", false),
new MinFlexCase(comp, "Vbox", false));
}
for (String inp : inps) {
outputCase(new VFlexCase(inp, true), new VFlexCase(inp, false));
outputCase(new LayoutCase(inp, "Hlayout", false),
new LayoutCase(inp, "Hbox", false),
new LayoutCase(inp, "Hlayout", true),
new LayoutCase(inp, "Hbox", true));
outputCase(new LayoutCase(inp, "Vlayout", false),
new LayoutCase(inp, "Vbox", false),
new LayoutCase(inp, "Vlayout", true),
new LayoutCase(inp, "Vbox", true));
outputCase(new MinFlexCase(inp, "Hlayout", false),
new MinFlexCase(inp, "Hbox", false),
new MinFlexCase(inp, "Hlayout", true),
new MinFlexCase(inp, "Hbox", true));
outputCase(new MinFlexCase(inp, "Vlayout", false),
new MinFlexCase(inp, "Vbox", false),
new MinFlexCase(inp, "Vlayout", true),
new MinFlexCase(inp, "Vbox", true));
outputCase(new InputHFlexCase(inp, false),
new InputHFlexCase(inp, true));
}
}
|
diff --git a/src/rajawali/renderer/RajawaliRenderer.java b/src/rajawali/renderer/RajawaliRenderer.java
index 54d0ed87..9cf3876b 100644
--- a/src/rajawali/renderer/RajawaliRenderer.java
+++ b/src/rajawali/renderer/RajawaliRenderer.java
@@ -1,768 +1,769 @@
package rajawali.renderer;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import rajawali.BaseObject3D;
import rajawali.Camera;
import rajawali.animation.Animation3D;
import rajawali.filters.IPostProcessingFilter;
import rajawali.materials.AMaterial;
import rajawali.materials.SimpleMaterial;
import rajawali.materials.SkyboxMaterial;
import rajawali.materials.TextureInfo;
import rajawali.materials.TextureManager;
import rajawali.math.Number3D;
import rajawali.primitives.Cube;
import rajawali.renderer.plugins.IRendererPlugin;
import rajawali.util.FPSUpdateListener;
import rajawali.util.ObjectColorPicker.ColorPickerInfo;
import rajawali.util.RajLog;
import rajawali.visitors.INode;
import rajawali.visitors.INodeVisitor;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.Matrix;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.WindowManager;
public class RajawaliRenderer implements GLSurfaceView.Renderer, INode {
protected final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000;
protected Context mContext;
protected float mEyeZ = 4.0f;
protected float mFrameRate;
protected double mLastMeasuredFPS;
protected FPSUpdateListener mFPSUpdateListener;
protected SharedPreferences preferences;
protected int mViewportWidth, mViewportHeight;
protected WallpaperService.Engine mWallpaperEngine;
protected GLSurfaceView mSurfaceView;
protected Timer mTimer;
protected int mFrameCount;
private long mStartTime = System.nanoTime();
private long mLastRender;
protected float[] mVMatrix = new float[16];
protected float[] mPMatrix = new float[16];
protected List<BaseObject3D> mChildren;
private List<Animation3D> mAnimations;
protected boolean mEnableDepthBuffer = true;
protected TextureManager mTextureManager;
protected PostProcessingRenderer mPostProcessingRenderer;
/**
* Deprecated. Use setSceneCachingEnabled(false) instead.
*/
@Deprecated
protected boolean mClearChildren = true;
/**
* The camera currently in use.
* Not thread safe for speed, should
* only be used by GL thread (onDrawFrame() and render())
* or prior to rendering such as initScene().
*/
protected Camera mCamera;
/**
* List of all cameras in the scene.
*/
protected List<Camera> mCameras;
/**
* Temporary camera which will be switched to by the GL thread.
* Guarded by mNextCameraLock
*/
protected Camera mNextCamera;
private final Object mNextCameraLock = new Object();
protected float mRed, mBlue, mGreen, mAlpha;
protected Cube mSkybox;
protected TextureInfo mSkyboxTextureInfo;
protected static int mMaxLights = 1;
protected ColorPickerInfo mPickerInfo;
protected List<IPostProcessingFilter> mFilters;
protected boolean mReloadPickerInfo;
protected static boolean mFogEnabled;
protected boolean mUsesCoverageAa;
public static boolean supportsUIntBuffers = false;
protected boolean mSceneInitialized;
/**
* Scene caching stores all textures and relevant OpenGL-specific
* data. This is used when the OpenGL context needs to be restored.
* The context typically needs to be restored when the application
* is re-activated or when a live wallpaper is rotated.
*/
private boolean mSceneCachingEnabled;
protected List<IRendererPlugin> mPlugins;
public RajawaliRenderer(Context context) {
RajLog.i("IMPORTANT: Rajawali's coordinate system has changed. It now reflects");
RajLog.i("the OpenGL standard. Please invert the camera's z coordinate or");
RajLog.i("call mCamera.setLookAt(0, 0, 0).");
AMaterial.setLoaderContext(context);
mContext = context;
mAnimations = Collections.synchronizedList(new CopyOnWriteArrayList<Animation3D>());
mChildren = Collections.synchronizedList(new CopyOnWriteArrayList<BaseObject3D>());
mFilters = Collections.synchronizedList(new CopyOnWriteArrayList<IPostProcessingFilter>());
mPlugins = Collections.synchronizedList(new CopyOnWriteArrayList<IRendererPlugin>());
mCamera = new Camera();
mCameras = Collections.synchronizedList(new CopyOnWriteArrayList<Camera>());
addCamera(mCamera);
mCamera.setZ(mEyeZ);
mAlpha = 0;
mSceneCachingEnabled = true;
mPostProcessingRenderer = new PostProcessingRenderer(this);
mFrameRate = getRefreshRate();
}
/**
* Register an animation to be managed by the renderer. This is optional leaving open the possibility to manage
* updates on Animations in your own implementation. Returns true on success.
*
* @param anim
* @return
*/
public boolean registerAnimation(Animation3D anim) {
return mAnimations.add(anim);
}
/**
* Remove a managed animation. Returns true on success.
*
* @param anim
* @return
*/
public boolean unregisterAnimation(Animation3D anim) {
return mAnimations.remove(anim);
}
/**
* Sets the camera currently being used to display the scene.
*
* @param mCamera Camera object to display the scene with.
*/
public void setCamera(Camera camera) {
synchronized (mNextCameraLock) {
mNextCamera = camera;
}
}
/**
* Sets the camera currently being used to display the scene.
*
* @param camera Index of the camera to use.
*/
public void setCamera(int camera) {
setCamera(mCameras.get(camera));
}
/**
* Fetches the camera currently being used to display the scene.
* Note that the camera is not thread safe so this should be used
* with extreme caution.
*
* @return Camera object currently used for the scene.
* @see {@link RajawaliRenderer#mCamera}
*/
public Camera getCamera() {
return this.mCamera;
}
/**
* Fetches the specified camera.
*
* @param camera Index of the camera to fetch.
* @return Camera which was retrieved.
*/
public Camera getCamera(int camera) {
return mCameras.get(camera);
}
/**
* Adds a camera to the renderer.
*
* @param camera Camera object to add.
* @return int The index the new camera was added at.
*/
public int addCamera(Camera camera) {
mCameras.add(camera);
return (mCameras.size() - 1);
}
/**
* Replaces a camera in the renderer at the specified location
* in the list. This does not validate the index, so if it is not
* contained in the list already, an exception will be thrown.
*
* @param camera Camera object to add.
* @param location Integer index of the camera to replace.
*/
public void replaceCamera(Camera camera, int location) {
mCameras.set(location, camera);
}
/**
* Adds a camera with the option to switch to it immediately
*
* @param camera The Camera to add.
* @param useNow Boolean indicating if we should switch to this
* camera immediately.
* @return int The index the new camera was added at.
*/
public int addCamera(Camera camera, boolean useNow) {
int index = addCamera(camera);
if (useNow) setCamera(camera);
return index;
}
/**
* Replaces a camera at the specified index with an option to switch to it
* immediately.
*
* @param camera The Camera to add.
* @param location The index of the camera to replace.
* @param useNow Boolean indicating if we should switch to this
* camera immediately.
*/
public void replaceCamera(Camera camera, int location, boolean useNow) {
replaceCamera(camera, location);
if (useNow) setCamera(camera);
}
public void requestColorPickingTexture(ColorPickerInfo pickerInfo) {
mPickerInfo = pickerInfo;
}
public void onDrawFrame(GL10 glUnused) {
synchronized (mNextCameraLock) {
//Check if we need to switch the camera, and if so, do it.
if (mNextCamera != null) {
mCamera = mNextCamera;
mNextCamera = null;
mCamera.setProjectionMatrix(mViewportWidth, mViewportHeight);
}
}
render();
++mFrameCount;
if (mFrameCount % 50 == 0) {
long now = System.nanoTime();
double elapsedS = (now - mStartTime) / 1.0e9;
double msPerFrame = (1000 * elapsedS / mFrameCount);
mLastMeasuredFPS = 1000 / msPerFrame;
//RajLog.d("ms / frame: " + msPerFrame + " - fps: " + mLastMeasuredFPS);
mFrameCount = 0;
mStartTime = now;
if(mFPSUpdateListener != null)
mFPSUpdateListener.onFPSUpdate(mLastMeasuredFPS);
}
}
private void render() {
final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d;
mLastRender = SystemClock.elapsedRealtime();
int clearMask = GLES20.GL_COLOR_BUFFER_BIT;
ColorPickerInfo pickerInfo = mPickerInfo;
mTextureManager.validateTextures();
if (pickerInfo != null) {
if(mReloadPickerInfo) pickerInfo.getPicker().reload();
mReloadPickerInfo = false;
pickerInfo.getPicker().bindFrameBuffer();
GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
} else {
if (mFilters.size() == 0)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
else {
if (mPostProcessingRenderer.isEnabled())
mPostProcessingRenderer.bind();
}
GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha);
}
if (mEnableDepthBuffer) {
clearMask |= GLES20.GL_DEPTH_BUFFER_BIT;
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDepthMask(true);
GLES20.glClearDepthf(1.0f);
}
if (mUsesCoverageAa) {
clearMask |= GL_COVERAGE_BUFFER_BIT_NV;
}
GLES20.glClear(clearMask);
mVMatrix = mCamera.getViewMatrix();
mPMatrix = mCamera.getProjectionMatrix();
if (mSkybox != null) {
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(false);
mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ());
mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (mEnableDepthBuffer) {
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(true);
}
}
mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane
// Update all registered animations
- for (int i = 0, j = mAnimations.size(); i < j; i++)
+ for (int i = 0; i < mAnimations.size(); i++) {
mAnimations.get(i).update(deltaTime);
+ }
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (pickerInfo != null) {
pickerInfo.getPicker().createColorPickingTexture(pickerInfo);
pickerInfo.getPicker().unbindFrameBuffer();
pickerInfo = null;
mPickerInfo = null;
render();
} else if (mPostProcessingRenderer.isEnabled()) {
mPostProcessingRenderer.render();
}
for (int i = 0, j = mPlugins.size(); i < j; i++)
mPlugins.get(i).render();
}
public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
}
public void onTouchEvent(MotionEvent event) {
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
mViewportWidth = width;
mViewportHeight = height;
mCamera.setProjectionMatrix(width, height);
GLES20.glViewport(0, 0, width, height);
}
/* Called when the OpenGL context is created or re-created. Don't set up your scene here,
* use initScene() for that.
*
* @see rajawali.renderer.RajawaliRenderer#initScene
* @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
supportsUIntBuffers = gl.glGetString(GL10.GL_EXTENSIONS).indexOf("GL_OES_element_index_uint") > -1;
GLES20.glFrontFace(GLES20.GL_CCW);
GLES20.glCullFace(GLES20.GL_BACK);
if (!mSceneInitialized) {
mTextureManager = new TextureManager(mContext);
initScene();
}
if (!mSceneCachingEnabled) {
mTextureManager.reset();
if (mChildren.size() > 0) {
mChildren.clear();
}
if (mPlugins.size() > 0) {
mPlugins.clear();
}
} else if(mSceneCachingEnabled && mSceneInitialized) {
mTextureManager.reload();
reloadChildren();
if(mSkybox != null)
mSkybox.reload();
if(mPostProcessingRenderer.isInitialized())
mPostProcessingRenderer.reload();
reloadPlugins();
mReloadPickerInfo = true;
}
mSceneInitialized = true;
startRendering();
}
private void reloadChildren() {
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).reload();
}
private void reloadPlugins() {
for (int i = 0, j = mPlugins.size(); i < j; i++)
mPlugins.get(i).reload();
}
/**
* Scene construction should happen here, not in onSurfaceCreated()
*/
protected void initScene() {
}
protected void destroyScene() {
mSceneInitialized = false;
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).destroy();
mChildren.clear();
for (int i = 0, j = mPlugins.size(); i < j; i++)
mPlugins.get(i).destroy();
mPlugins.clear();
}
public void startRendering() {
mLastRender = SystemClock.elapsedRealtime();
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
}
mTimer = new Timer();
mTimer.schedule(new RequestRenderTask(), 0, (long) (1000 / mFrameRate));
}
/**
* Stop rendering the scene.
*
* @return true if rendering was stopped, false if rendering was already
* stopped (no action taken)
*/
protected boolean stopRendering() {
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
mTimer = null;
return true;
}
return false;
}
public void onVisibilityChanged(boolean visible) {
if (!visible) {
stopRendering();
} else
startRendering();
}
public void onSurfaceDestroyed() {
stopRendering();
if (mTextureManager != null)
mTextureManager.reset();
destroyScene();
}
public void setSharedPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
private class RequestRenderTask extends TimerTask {
public void run() {
if (mSurfaceView != null) {
mSurfaceView.requestRender();
}
}
}
public Number3D unProject(float x, float y, float z) {
x = mViewportWidth - x;
y = mViewportHeight - y;
float[] m = new float[16], mvpmatrix = new float[16],
in = new float[4],
out = new float[4];
Matrix.multiplyMM(mvpmatrix, 0, mPMatrix, 0, mVMatrix, 0);
Matrix.invertM(m, 0, mvpmatrix, 0);
in[0] = (x / (float)mViewportWidth) * 2 - 1;
in[1] = (y / (float)mViewportHeight) * 2 - 1;
in[2] = 2 * z - 1;
in[3] = 1;
Matrix.multiplyMV(out, 0, m, 0, in, 0);
if (out[3]==0)
return null;
out[3] = 1/out[3];
return new Number3D(out[0] * out[3], out[1] * out[3], out[2] * out[3]);
}
public float getFrameRate() {
return mFrameRate;
}
public void setFrameRate(int frameRate) {
setFrameRate((float)frameRate);
}
public void setFrameRate(float frameRate) {
this.mFrameRate = frameRate;
if (stopRendering()) {
// Restart timer with new frequency
startRendering();
}
}
public float getRefreshRate() {
return ((WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay()
.getRefreshRate();
}
public WallpaperService.Engine getEngine() {
return mWallpaperEngine;
}
public void setEngine(WallpaperService.Engine engine) {
this.mWallpaperEngine = engine;
}
public GLSurfaceView getSurfaceView() {
return mSurfaceView;
}
public void setSurfaceView(GLSurfaceView surfaceView) {
this.mSurfaceView = surfaceView;
}
public Context getContext() {
return mContext;
}
public TextureManager getTextureManager() {
return mTextureManager;
}
public void addChild(BaseObject3D child) {
mChildren.add(child);
}
public void clearChildren() {
mChildren.clear();
}
public void addPlugin(IRendererPlugin plugin) {
mPlugins.add(plugin);
}
public void clearPlugins() {
mPlugins.clear();
}
protected void setSkybox(int resourceId) {
mCamera.setFarPlane(1000);
mSkybox = new Cube(700, true, false);
mSkybox.setDoubleSided(true);
mSkyboxTextureInfo = mTextureManager.addTexture(BitmapFactory.decodeResource(mContext.getResources(), resourceId));
SimpleMaterial material = new SimpleMaterial();
material.addTexture(mSkyboxTextureInfo);
mSkybox.setMaterial(material);
}
protected void setSkybox(int front, int right, int back, int left, int up, int down) {
mCamera.setFarPlane(1000);
mSkybox = new Cube(700, true);
Bitmap[] textures = new Bitmap[6];
textures[0] = BitmapFactory.decodeResource(mContext.getResources(), left);
textures[1] = BitmapFactory.decodeResource(mContext.getResources(), right);
textures[2] = BitmapFactory.decodeResource(mContext.getResources(), up);
textures[3] = BitmapFactory.decodeResource(mContext.getResources(), down);
textures[4] = BitmapFactory.decodeResource(mContext.getResources(), front);
textures[5] = BitmapFactory.decodeResource(mContext.getResources(), back);
mSkyboxTextureInfo = mTextureManager.addCubemapTextures(textures);
SkyboxMaterial mat = new SkyboxMaterial();
mat.addTexture(mSkyboxTextureInfo);
mSkybox.setMaterial(mat);
}
protected void updateSkybox(int resourceId) {
mTextureManager.updateTexture(mSkyboxTextureInfo, BitmapFactory.decodeResource(mContext.getResources(), resourceId));
}
protected void updateSkybox(int front, int right, int back, int left, int up, int down) {
Bitmap[] textures = new Bitmap[6];
textures[0] = BitmapFactory.decodeResource(mContext.getResources(), left);
textures[1] = BitmapFactory.decodeResource(mContext.getResources(), right);
textures[2] = BitmapFactory.decodeResource(mContext.getResources(), up);
textures[3] = BitmapFactory.decodeResource(mContext.getResources(), down);
textures[4] = BitmapFactory.decodeResource(mContext.getResources(), front);
textures[5] = BitmapFactory.decodeResource(mContext.getResources(), back);
mTextureManager.updateCubemapTextures(mSkyboxTextureInfo, textures);
}
public boolean removeChild(BaseObject3D child) {
return mChildren.remove(child);
}
public boolean removePlugin(IRendererPlugin plugin) {
return mPlugins.remove(plugin);
}
public int getNumPlugins() {
return mPlugins.size();
}
public List<IRendererPlugin> getPlugins() {
return mPlugins;
}
public boolean hasPlugin(IRendererPlugin plugin) {
return mPlugins.contains(plugin);
}
public int getNumChildren() {
return mChildren.size();
}
public List<BaseObject3D> getChildren() {
return mChildren;
}
protected boolean hasChild(BaseObject3D child) {
return mChildren.contains(child);
}
public void addPostProcessingFilter(IPostProcessingFilter filter) {
if(mFilters.size() > 0)
mFilters.remove(0);
mFilters.add(filter);
mPostProcessingRenderer.setEnabled(true);
mPostProcessingRenderer.setFilter(filter);
}
public void accept(INodeVisitor visitor) {
visitor.apply(this);
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).accept(visitor);
}
public void removePostProcessingFilter(IPostProcessingFilter filter) {
mFilters.remove(filter);
}
public void clearPostProcessingFilters() {
mFilters.clear();
mPostProcessingRenderer.unbind();
mPostProcessingRenderer.destroy();
mPostProcessingRenderer = new PostProcessingRenderer(this);
}
public int getViewportWidth() {
return mViewportWidth;
}
public int getViewportHeight() {
return mViewportHeight;
}
public void setBackgroundColor(float red, float green, float blue, float alpha) {
mRed = red;
mGreen = green;
mBlue = blue;
mAlpha = alpha;
}
public void setBackgroundColor(int color) {
setBackgroundColor(Color.red(color) / 255f, Color.green(color) / 255f, Color.blue(color) / 255f, Color.alpha(color) / 255f);
}
public boolean getSceneInitialized() {
return mSceneInitialized;
}
public void setSceneCachingEnabled(boolean enabled) {
mSceneCachingEnabled = enabled;
}
public boolean getSceneCachingEnabled() {
return mSceneCachingEnabled;
}
public void setFogEnabled(boolean enabled) {
mFogEnabled = enabled;
mCamera.setFogEnabled(enabled);
}
public void setUsesCoverageAa(boolean value) {
mUsesCoverageAa = value;
}
public static boolean isFogEnabled() {
return mFogEnabled;
}
public static int getMaxLights() {
return mMaxLights;
}
public static void setMaxLights(int maxLights) {
RajawaliRenderer.mMaxLights = maxLights;
}
public void setFPSUpdateListener(FPSUpdateListener listener) {
mFPSUpdateListener = listener;
}
public static int checkGLError(String message) {
int error = GLES20.glGetError();
if(error != GLES20.GL_NO_ERROR)
{
StringBuffer sb = new StringBuffer();
if(message != null)
sb.append("[").append(message).append("] ");
sb.append("GLES20 Error: ");
sb.append(GLU.gluErrorString(error));
RajLog.e(sb.toString());
}
return error;
}
public int getNumTriangles() {
int triangleCount = 0;
for (int i = 0; i < mChildren.size(); i++) {
if (mChildren.get(i).getGeometry() != null && mChildren.get(i).getGeometry().getVertices() != null && mChildren.get(i).isVisible())
triangleCount += mChildren.get(i).getGeometry().getVertices().limit() / 9;
}
return triangleCount;
}
}
| false | true | private void render() {
final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d;
mLastRender = SystemClock.elapsedRealtime();
int clearMask = GLES20.GL_COLOR_BUFFER_BIT;
ColorPickerInfo pickerInfo = mPickerInfo;
mTextureManager.validateTextures();
if (pickerInfo != null) {
if(mReloadPickerInfo) pickerInfo.getPicker().reload();
mReloadPickerInfo = false;
pickerInfo.getPicker().bindFrameBuffer();
GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
} else {
if (mFilters.size() == 0)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
else {
if (mPostProcessingRenderer.isEnabled())
mPostProcessingRenderer.bind();
}
GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha);
}
if (mEnableDepthBuffer) {
clearMask |= GLES20.GL_DEPTH_BUFFER_BIT;
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDepthMask(true);
GLES20.glClearDepthf(1.0f);
}
if (mUsesCoverageAa) {
clearMask |= GL_COVERAGE_BUFFER_BIT_NV;
}
GLES20.glClear(clearMask);
mVMatrix = mCamera.getViewMatrix();
mPMatrix = mCamera.getProjectionMatrix();
if (mSkybox != null) {
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(false);
mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ());
mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (mEnableDepthBuffer) {
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(true);
}
}
mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane
// Update all registered animations
for (int i = 0, j = mAnimations.size(); i < j; i++)
mAnimations.get(i).update(deltaTime);
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (pickerInfo != null) {
pickerInfo.getPicker().createColorPickingTexture(pickerInfo);
pickerInfo.getPicker().unbindFrameBuffer();
pickerInfo = null;
mPickerInfo = null;
render();
} else if (mPostProcessingRenderer.isEnabled()) {
mPostProcessingRenderer.render();
}
for (int i = 0, j = mPlugins.size(); i < j; i++)
mPlugins.get(i).render();
}
| private void render() {
final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d;
mLastRender = SystemClock.elapsedRealtime();
int clearMask = GLES20.GL_COLOR_BUFFER_BIT;
ColorPickerInfo pickerInfo = mPickerInfo;
mTextureManager.validateTextures();
if (pickerInfo != null) {
if(mReloadPickerInfo) pickerInfo.getPicker().reload();
mReloadPickerInfo = false;
pickerInfo.getPicker().bindFrameBuffer();
GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
} else {
if (mFilters.size() == 0)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
else {
if (mPostProcessingRenderer.isEnabled())
mPostProcessingRenderer.bind();
}
GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha);
}
if (mEnableDepthBuffer) {
clearMask |= GLES20.GL_DEPTH_BUFFER_BIT;
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDepthMask(true);
GLES20.glClearDepthf(1.0f);
}
if (mUsesCoverageAa) {
clearMask |= GL_COVERAGE_BUFFER_BIT_NV;
}
GLES20.glClear(clearMask);
mVMatrix = mCamera.getViewMatrix();
mPMatrix = mCamera.getProjectionMatrix();
if (mSkybox != null) {
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(false);
mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ());
mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (mEnableDepthBuffer) {
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(true);
}
}
mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane
// Update all registered animations
for (int i = 0; i < mAnimations.size(); i++) {
mAnimations.get(i).update(deltaTime);
}
for (int i = 0; i < mChildren.size(); i++)
mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo);
if (pickerInfo != null) {
pickerInfo.getPicker().createColorPickingTexture(pickerInfo);
pickerInfo.getPicker().unbindFrameBuffer();
pickerInfo = null;
mPickerInfo = null;
render();
} else if (mPostProcessingRenderer.isEnabled()) {
mPostProcessingRenderer.render();
}
for (int i = 0, j = mPlugins.size(); i < j; i++)
mPlugins.get(i).render();
}
|
diff --git a/src/minecraft/ml/boxes/client/ModelBox.java b/src/minecraft/ml/boxes/client/ModelBox.java
index 2102640..f8cb548 100644
--- a/src/minecraft/ml/boxes/client/ModelBox.java
+++ b/src/minecraft/ml/boxes/client/ModelBox.java
@@ -1,72 +1,72 @@
package ml.boxes.client;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
public class ModelBox extends ModelBase {
private int texX = 128;
private int texY = 128;
public ModelRenderer bottom;
public ModelRenderer flap1; //X+
public ModelRenderer flap2; //X-
public ModelRenderer flap3; //Z-
public ModelRenderer flap4; //Z+
public ModelRenderer[] sides = new ModelRenderer[4];
public ModelBox() {
bottom = new ModelRenderer(this, 0, 0).setTextureSize(texX, texY);
bottom.addBox(0F, 0F, 0F, 12, 1, 12, 0.0F);
bottom.rotationPointX = 2F;
bottom.rotationPointZ = 2F;
flap1 = new ModelRenderer(this, 0, 45).setTextureSize(texX, texY);
flap1.addBox(0F, -0.5F, 0F, 12, 1, 6);
flap1.rotationPointX = 2F;
flap1.rotationPointY = 13.5F;
flap1.rotationPointZ = 2F;
flap2 = new ModelRenderer(this, 38, 45).setTextureSize(texX, texY);
flap2.addBox(0F, -0.5F, -6F, 12, 1, 6);
flap2.rotationPointX = 2F;
flap2.rotationPointY = 13.5F;
flap2.rotationPointZ = 14F;
flap3 = new ModelRenderer(this, 0, 54).setTextureSize(texX, texY);
flap3.addBox(0F, -0.5F, 0F, 6, 1, 12);
flap3.rotationPointX = 2F;
flap3.rotationPointY = 13.4F;
flap3.rotationPointZ = 2F;
flap4 = new ModelRenderer(this, 38, 54).setTextureSize(texX, texY);
flap4.addBox(-6F, -0.5F, 0F, 6, 1, 12);
flap4.rotationPointX = 14F;
flap4.rotationPointY = 13.4F;
flap4.rotationPointZ = 2F;
for (int i=0; i<4; i++){
ModelRenderer side = new ModelRenderer(this, i*32, 15).setTextureSize(texX, texY);
side.addBox(-7F, 0F, -7F, 1, 14, 14);
side.rotationPointX = 8F;
side.rotationPointY = 0F;
- side.rotationPointZ = 10F;
+ side.rotationPointZ = 8F;
side.rotateAngleY = (float)(i*(Math.PI/2));
sides[i] = side;
}
}
public void renderAll(){
bottom.render(0.0625F);
flap1.render(0.0625F);
flap2.render(0.0625F);
flap3.render(0.0625F);
flap4.render(0.0625F);
for (ModelRenderer mr : sides){
mr.render(0.0625F);
}
}
}
| true | true | public ModelBox() {
bottom = new ModelRenderer(this, 0, 0).setTextureSize(texX, texY);
bottom.addBox(0F, 0F, 0F, 12, 1, 12, 0.0F);
bottom.rotationPointX = 2F;
bottom.rotationPointZ = 2F;
flap1 = new ModelRenderer(this, 0, 45).setTextureSize(texX, texY);
flap1.addBox(0F, -0.5F, 0F, 12, 1, 6);
flap1.rotationPointX = 2F;
flap1.rotationPointY = 13.5F;
flap1.rotationPointZ = 2F;
flap2 = new ModelRenderer(this, 38, 45).setTextureSize(texX, texY);
flap2.addBox(0F, -0.5F, -6F, 12, 1, 6);
flap2.rotationPointX = 2F;
flap2.rotationPointY = 13.5F;
flap2.rotationPointZ = 14F;
flap3 = new ModelRenderer(this, 0, 54).setTextureSize(texX, texY);
flap3.addBox(0F, -0.5F, 0F, 6, 1, 12);
flap3.rotationPointX = 2F;
flap3.rotationPointY = 13.4F;
flap3.rotationPointZ = 2F;
flap4 = new ModelRenderer(this, 38, 54).setTextureSize(texX, texY);
flap4.addBox(-6F, -0.5F, 0F, 6, 1, 12);
flap4.rotationPointX = 14F;
flap4.rotationPointY = 13.4F;
flap4.rotationPointZ = 2F;
for (int i=0; i<4; i++){
ModelRenderer side = new ModelRenderer(this, i*32, 15).setTextureSize(texX, texY);
side.addBox(-7F, 0F, -7F, 1, 14, 14);
side.rotationPointX = 8F;
side.rotationPointY = 0F;
side.rotationPointZ = 10F;
side.rotateAngleY = (float)(i*(Math.PI/2));
sides[i] = side;
}
}
| public ModelBox() {
bottom = new ModelRenderer(this, 0, 0).setTextureSize(texX, texY);
bottom.addBox(0F, 0F, 0F, 12, 1, 12, 0.0F);
bottom.rotationPointX = 2F;
bottom.rotationPointZ = 2F;
flap1 = new ModelRenderer(this, 0, 45).setTextureSize(texX, texY);
flap1.addBox(0F, -0.5F, 0F, 12, 1, 6);
flap1.rotationPointX = 2F;
flap1.rotationPointY = 13.5F;
flap1.rotationPointZ = 2F;
flap2 = new ModelRenderer(this, 38, 45).setTextureSize(texX, texY);
flap2.addBox(0F, -0.5F, -6F, 12, 1, 6);
flap2.rotationPointX = 2F;
flap2.rotationPointY = 13.5F;
flap2.rotationPointZ = 14F;
flap3 = new ModelRenderer(this, 0, 54).setTextureSize(texX, texY);
flap3.addBox(0F, -0.5F, 0F, 6, 1, 12);
flap3.rotationPointX = 2F;
flap3.rotationPointY = 13.4F;
flap3.rotationPointZ = 2F;
flap4 = new ModelRenderer(this, 38, 54).setTextureSize(texX, texY);
flap4.addBox(-6F, -0.5F, 0F, 6, 1, 12);
flap4.rotationPointX = 14F;
flap4.rotationPointY = 13.4F;
flap4.rotationPointZ = 2F;
for (int i=0; i<4; i++){
ModelRenderer side = new ModelRenderer(this, i*32, 15).setTextureSize(texX, texY);
side.addBox(-7F, 0F, -7F, 1, 14, 14);
side.rotationPointX = 8F;
side.rotationPointY = 0F;
side.rotationPointZ = 8F;
side.rotateAngleY = (float)(i*(Math.PI/2));
sides[i] = side;
}
}
|
diff --git a/ca/src/main/java/org/codeartisans/qipki/ca/QiPkiCaAssembler.java b/ca/src/main/java/org/codeartisans/qipki/ca/QiPkiCaAssembler.java
index 9eb5ce1..c04a5c9 100644
--- a/ca/src/main/java/org/codeartisans/qipki/ca/QiPkiCaAssembler.java
+++ b/ca/src/main/java/org/codeartisans/qipki/ca/QiPkiCaAssembler.java
@@ -1,260 +1,262 @@
/*
* Copyright (c) 2010 Paul Merlin <[email protected]>
*
* 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 org.codeartisans.qipki.ca;
import org.codeartisans.qipki.ca.application.contexts.CAContext;
import org.codeartisans.qipki.ca.application.contexts.CAListContext;
import org.codeartisans.qipki.ca.application.contexts.CryptoStoreContext;
import org.codeartisans.qipki.ca.application.contexts.CryptoStoreListContext;
import org.codeartisans.qipki.ca.application.contexts.RootContext;
import org.codeartisans.qipki.ca.domain.ca.CAEntity;
import org.codeartisans.qipki.ca.domain.ca.CAFactory;
import org.codeartisans.qipki.ca.domain.ca.CARepository;
import org.codeartisans.qipki.ca.domain.cryptostore.CryptoStoreEntity;
import org.codeartisans.qipki.ca.domain.cryptostore.CryptoStoreFactory;
import org.codeartisans.qipki.ca.domain.cryptostore.CryptoStoreRepository;
import org.codeartisans.qipki.ca.presentation.http.HttpService;
import org.codeartisans.qipki.ca.presentation.http.RootServletService;
import org.codeartisans.qipki.ca.presentation.rest.RestletApplication;
import org.codeartisans.qipki.ca.presentation.rest.RestletFinder;
import org.codeartisans.qipki.ca.presentation.rest.RestletServletServerService;
import org.codeartisans.qipki.ca.presentation.rest.RestValuesFactory;
import org.codeartisans.qipki.ca.presentation.rest.resources.ApiRootResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.ca.CAFactoryResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.ca.CAListResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.ca.CAResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.ca.PKCS10SignerResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.cryptostore.CryptoStoreFactoryResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.cryptostore.CryptoStoreListResource;
import org.codeartisans.qipki.ca.presentation.rest.resources.cryptostore.CryptoStoreResource;
import org.codeartisans.qipki.commons.QiPkiCommonsValuesAssembler;
import org.codeartisans.qipki.core.crypto.CryptGEN;
import org.codeartisans.qipki.core.crypto.CryptIO;
import org.qi4j.api.common.Visibility;
import org.qi4j.bootstrap.ApplicationAssembler;
import org.qi4j.bootstrap.ApplicationAssembly;
import org.qi4j.bootstrap.ApplicationAssemblyFactory;
import org.qi4j.bootstrap.Assembler;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.LayerAssembly;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.entitystore.memory.MemoryEntityStoreService;
import org.qi4j.index.rdf.assembly.RdfMemoryStoreAssembler;
import org.qi4j.library.http.JettyConfiguration;
import static org.qi4j.library.http.Dispatchers.Dispatcher.*;
import static org.qi4j.library.http.Servlets.*;
import org.qi4j.library.http.UnitOfWorkFilterService;
import org.qi4j.spi.uuid.UuidIdentityGeneratorService;
public class QiPkiCaAssembler
implements ApplicationAssembler
{
@Override
public final ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
throws AssemblyException
{
ApplicationAssembly app = applicationFactory.newApplicationAssembly();
app.setName( "QiPKIServer" );
app.setVersion( "1.0-SNAPSHOT" );
LayerAssembly presentation = app.layerAssembly( "presentation" );
{
assembleDevTestModule( presentation.moduleAssembly( "test" ) );
new Assembler() // REST
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RestletApplication.class ).
visibleIn( Visibility.layer );
module.addObjects( RestletFinder.class,
ApiRootResource.class,
CryptoStoreListResource.class,
CryptoStoreFactoryResource.class,
CryptoStoreResource.class,
CAListResource.class,
CAFactoryResource.class,
CAResource.class,
PKCS10SignerResource.class ).
visibleIn( Visibility.module );
new QiPkiCommonsValuesAssembler( Visibility.layer ).assemble( module );
module.addServices( RestValuesFactory.class ).
visibleIn( Visibility.module );
addServlets( serve( "/api/*" ).with( RestletServletServerService.class ) ).
to( module );
addFilters( filter( "/api/*" ).through( UnitOfWorkFilterService.class ).
on( REQUEST ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "rest" ) );
new Assembler() // Http Service
{
// NOTE Servlets are added with layer visibility
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( HttpService.class ).
visibleIn( Visibility.module ).
instantiateOnStartup();
addServlets( serve( "/" ).with( RootServletService.class ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "http" ) );
new Assembler() // UI Configuration
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class ).
visibleIn( Visibility.layer );
module.addEntities( JettyConfiguration.class ).
visibleIn( Visibility.layer );
}
}.assemble( presentation.moduleAssembly( "config" ) );
}
LayerAssembly application = app.layerAssembly( "application" );
{
new Assembler()
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RootContext.class,
CryptoStoreListContext.class,
CryptoStoreContext.class,
CAListContext.class,
CAContext.class ).
visibleIn( Visibility.application );
}
}.assemble( application.moduleAssembly( "dci" ) );
}
LayerAssembly domain = app.layerAssembly( "domain" );
{
new Assembler() // CertificateAuthority
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.addEntities( CAEntity.class );
+ module.addEntities( CAEntity.class ).
+ visibleIn( Visibility.application );
module.addServices( CARepository.class,
CAFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "ca" ) );
new Assembler() // CryptoStore
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
- module.addEntities( CryptoStoreEntity.class );
+ module.addEntities( CryptoStoreEntity.class ).
+ visibleIn( Visibility.application );
module.addServices( CryptoStoreRepository.class,
CryptoStoreFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "cryptostore" ) );
}
LayerAssembly crypto = app.layerAssembly( "crypto" );
{
new Assembler() // Crypto
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addTransients( CryptIO.class,
CryptGEN.class ).
visibleIn( Visibility.application );
}
}.assemble( crypto.moduleAssembly( "crypto" ) );
}
LayerAssembly infrastructure = app.layerAssembly( "infrastructure" );
{
new Assembler() // Store
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class,
UuidIdentityGeneratorService.class ).
visibleIn( Visibility.application );
new RdfMemoryStoreAssembler( null, Visibility.application, Visibility.application ).assemble( module );
}
}.assemble( infrastructure.moduleAssembly( "store" ) );
}
presentation.uses( application, crypto );
- application.uses( domain );
+ application.uses( domain, crypto );
domain.uses( crypto, infrastructure );
presentation.uses( domain ); // TODO remove .. needed by fixtures .. need to rewrite fixtures to use DCI application code directly
return app;
}
protected void assembleDevTestModule( ModuleAssembly devTestModule )
throws AssemblyException
{
}
}
| false | true | public final ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
throws AssemblyException
{
ApplicationAssembly app = applicationFactory.newApplicationAssembly();
app.setName( "QiPKIServer" );
app.setVersion( "1.0-SNAPSHOT" );
LayerAssembly presentation = app.layerAssembly( "presentation" );
{
assembleDevTestModule( presentation.moduleAssembly( "test" ) );
new Assembler() // REST
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RestletApplication.class ).
visibleIn( Visibility.layer );
module.addObjects( RestletFinder.class,
ApiRootResource.class,
CryptoStoreListResource.class,
CryptoStoreFactoryResource.class,
CryptoStoreResource.class,
CAListResource.class,
CAFactoryResource.class,
CAResource.class,
PKCS10SignerResource.class ).
visibleIn( Visibility.module );
new QiPkiCommonsValuesAssembler( Visibility.layer ).assemble( module );
module.addServices( RestValuesFactory.class ).
visibleIn( Visibility.module );
addServlets( serve( "/api/*" ).with( RestletServletServerService.class ) ).
to( module );
addFilters( filter( "/api/*" ).through( UnitOfWorkFilterService.class ).
on( REQUEST ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "rest" ) );
new Assembler() // Http Service
{
// NOTE Servlets are added with layer visibility
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( HttpService.class ).
visibleIn( Visibility.module ).
instantiateOnStartup();
addServlets( serve( "/" ).with( RootServletService.class ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "http" ) );
new Assembler() // UI Configuration
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class ).
visibleIn( Visibility.layer );
module.addEntities( JettyConfiguration.class ).
visibleIn( Visibility.layer );
}
}.assemble( presentation.moduleAssembly( "config" ) );
}
LayerAssembly application = app.layerAssembly( "application" );
{
new Assembler()
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RootContext.class,
CryptoStoreListContext.class,
CryptoStoreContext.class,
CAListContext.class,
CAContext.class ).
visibleIn( Visibility.application );
}
}.assemble( application.moduleAssembly( "dci" ) );
}
LayerAssembly domain = app.layerAssembly( "domain" );
{
new Assembler() // CertificateAuthority
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addEntities( CAEntity.class );
module.addServices( CARepository.class,
CAFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "ca" ) );
new Assembler() // CryptoStore
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addEntities( CryptoStoreEntity.class );
module.addServices( CryptoStoreRepository.class,
CryptoStoreFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "cryptostore" ) );
}
LayerAssembly crypto = app.layerAssembly( "crypto" );
{
new Assembler() // Crypto
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addTransients( CryptIO.class,
CryptGEN.class ).
visibleIn( Visibility.application );
}
}.assemble( crypto.moduleAssembly( "crypto" ) );
}
LayerAssembly infrastructure = app.layerAssembly( "infrastructure" );
{
new Assembler() // Store
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class,
UuidIdentityGeneratorService.class ).
visibleIn( Visibility.application );
new RdfMemoryStoreAssembler( null, Visibility.application, Visibility.application ).assemble( module );
}
}.assemble( infrastructure.moduleAssembly( "store" ) );
}
presentation.uses( application, crypto );
application.uses( domain );
domain.uses( crypto, infrastructure );
presentation.uses( domain ); // TODO remove .. needed by fixtures .. need to rewrite fixtures to use DCI application code directly
return app;
}
| public final ApplicationAssembly assemble( ApplicationAssemblyFactory applicationFactory )
throws AssemblyException
{
ApplicationAssembly app = applicationFactory.newApplicationAssembly();
app.setName( "QiPKIServer" );
app.setVersion( "1.0-SNAPSHOT" );
LayerAssembly presentation = app.layerAssembly( "presentation" );
{
assembleDevTestModule( presentation.moduleAssembly( "test" ) );
new Assembler() // REST
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RestletApplication.class ).
visibleIn( Visibility.layer );
module.addObjects( RestletFinder.class,
ApiRootResource.class,
CryptoStoreListResource.class,
CryptoStoreFactoryResource.class,
CryptoStoreResource.class,
CAListResource.class,
CAFactoryResource.class,
CAResource.class,
PKCS10SignerResource.class ).
visibleIn( Visibility.module );
new QiPkiCommonsValuesAssembler( Visibility.layer ).assemble( module );
module.addServices( RestValuesFactory.class ).
visibleIn( Visibility.module );
addServlets( serve( "/api/*" ).with( RestletServletServerService.class ) ).
to( module );
addFilters( filter( "/api/*" ).through( UnitOfWorkFilterService.class ).
on( REQUEST ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "rest" ) );
new Assembler() // Http Service
{
// NOTE Servlets are added with layer visibility
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( HttpService.class ).
visibleIn( Visibility.module ).
instantiateOnStartup();
addServlets( serve( "/" ).with( RootServletService.class ) ).
to( module );
}
}.assemble( presentation.moduleAssembly( "http" ) );
new Assembler() // UI Configuration
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class ).
visibleIn( Visibility.layer );
module.addEntities( JettyConfiguration.class ).
visibleIn( Visibility.layer );
}
}.assemble( presentation.moduleAssembly( "config" ) );
}
LayerAssembly application = app.layerAssembly( "application" );
{
new Assembler()
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addObjects( RootContext.class,
CryptoStoreListContext.class,
CryptoStoreContext.class,
CAListContext.class,
CAContext.class ).
visibleIn( Visibility.application );
}
}.assemble( application.moduleAssembly( "dci" ) );
}
LayerAssembly domain = app.layerAssembly( "domain" );
{
new Assembler() // CertificateAuthority
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addEntities( CAEntity.class ).
visibleIn( Visibility.application );
module.addServices( CARepository.class,
CAFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "ca" ) );
new Assembler() // CryptoStore
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addEntities( CryptoStoreEntity.class ).
visibleIn( Visibility.application );
module.addServices( CryptoStoreRepository.class,
CryptoStoreFactory.class ).
visibleIn( Visibility.application );
}
}.assemble( domain.moduleAssembly( "cryptostore" ) );
}
LayerAssembly crypto = app.layerAssembly( "crypto" );
{
new Assembler() // Crypto
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addTransients( CryptIO.class,
CryptGEN.class ).
visibleIn( Visibility.application );
}
}.assemble( crypto.moduleAssembly( "crypto" ) );
}
LayerAssembly infrastructure = app.layerAssembly( "infrastructure" );
{
new Assembler() // Store
{
@Override
public void assemble( ModuleAssembly module )
throws AssemblyException
{
module.addServices( MemoryEntityStoreService.class,
UuidIdentityGeneratorService.class ).
visibleIn( Visibility.application );
new RdfMemoryStoreAssembler( null, Visibility.application, Visibility.application ).assemble( module );
}
}.assemble( infrastructure.moduleAssembly( "store" ) );
}
presentation.uses( application, crypto );
application.uses( domain, crypto );
domain.uses( crypto, infrastructure );
presentation.uses( domain ); // TODO remove .. needed by fixtures .. need to rewrite fixtures to use DCI application code directly
return app;
}
|
diff --git a/sm/src/main/java/com/semaphore/sm/SMGestureListener.java b/sm/src/main/java/com/semaphore/sm/SMGestureListener.java
index 5abfc51..4758012 100644
--- a/sm/src/main/java/com/semaphore/sm/SMGestureListener.java
+++ b/sm/src/main/java/com/semaphore/sm/SMGestureListener.java
@@ -1,46 +1,48 @@
/* Semaphore Manager
*
* Copyright (c) 2012 - 2014 Stratos Karafotis ([email protected])
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
package com.semaphore.sm;
import android.app.Activity;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class SMGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 120;
private static final int SWIPE_OFF_PATH_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 80;
private Activity activity;
public SMGestureListener(Activity activity) {
this.activity = activity;
}
@Override
public boolean onDown(MotionEvent event) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+ if (e1 == null || e2 == null)
+ return false;
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceY) < SWIPE_OFF_PATH_THRESHOLD
&& Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
((MainActivity) activity).handleSwipeRightToLeft();
else
((MainActivity) activity).handleSwipeLeftToRight();
return true;
}
return false;
}
}
| true | true | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceY) < SWIPE_OFF_PATH_THRESHOLD
&& Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
((MainActivity) activity).handleSwipeRightToLeft();
else
((MainActivity) activity).handleSwipeLeftToRight();
return true;
}
return false;
}
| public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 == null || e2 == null)
return false;
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceY) < SWIPE_OFF_PATH_THRESHOLD
&& Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
((MainActivity) activity).handleSwipeRightToLeft();
else
((MainActivity) activity).handleSwipeLeftToRight();
return true;
}
return false;
}
|
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/actionmanager/Request.java b/ambari-server/src/main/java/org/apache/ambari/server/actionmanager/Request.java
index e4de0cb08..5116ea972 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/actionmanager/Request.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/actionmanager/Request.java
@@ -1,304 +1,306 @@
/*
* 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.ambari.server.actionmanager;
import com.google.gson.Gson;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.controller.ExecuteActionRequest;
import org.apache.ambari.server.orm.entities.RequestEntity;
import org.apache.ambari.server.orm.entities.StageEntity;
import org.apache.ambari.server.state.Clusters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Request {
private static final Logger LOG = LoggerFactory.getLogger(Request.class);
private final long requestId;
private final long clusterId;
private final String clusterName;
private Long requestScheduleId;
private String commandName;
private String requestContext;
private long createTime;
private long startTime;
private long endTime;
private String inputs;
private String targetService;
private String targetComponent;
private String targetHosts;
private RequestType requestType;
private Collection<Stage> stages = new ArrayList<Stage>();
@AssistedInject
/**
* Construct new entity
*/
public Request(@Assisted long requestId, @Assisted("clusterId") Long clusterId, Clusters clusters) {
this.requestId = requestId;
this.clusterId = clusterId;
this.createTime = System.currentTimeMillis();
this.startTime = -1;
this.endTime = -1;
try {
this.clusterName = clusters.getClusterById(clusterId).getClusterName();
} catch (AmbariException e) {
String message = String.format("Cluster with id=%s not found", clusterId);
LOG.error(message);
throw new RuntimeException(message);
}
}
@AssistedInject
/**
* Construct new entity from stages provided
*/
//TODO remove when not needed
public Request(@Assisted Collection<Stage> stages, Clusters clusters){
if (stages != null && !stages.isEmpty()) {
this.stages.addAll(stages);
Stage stage = stages.iterator().next();
this.requestId = stage.getRequestId();
this.clusterName = stage.getClusterName();
try {
this.clusterId = clusters.getCluster(clusterName).getClusterId();
} catch (AmbariException e) {
String message = String.format("Cluster %s not found", clusterName);
LOG.error(message);
throw new RuntimeException(message);
}
this.requestContext = stages.iterator().next().getRequestContext();
this.createTime = System.currentTimeMillis();
this.startTime = -1;
this.endTime = -1;
this.requestType = RequestType.INTERNAL_REQUEST;
} else {
String message = "Attempted to construct request from empty stage collection";
LOG.error(message);
throw new RuntimeException(message);
}
}
@AssistedInject
/**
* Construct new entity from stages provided
*/
//TODO remove when not needed
public Request(@Assisted Collection<Stage> stages, @Assisted ExecuteActionRequest actionRequest,
Clusters clusters, Gson gson) throws AmbariException {
this(stages, clusters);
if (actionRequest != null) {
this.targetService = actionRequest.getServiceName();
this.targetComponent = actionRequest.getComponentName();
this.targetHosts = gson.toJson(actionRequest.getHosts());
this.inputs = gson.toJson(actionRequest.getParameters());
this.requestType = actionRequest.isCommand() ? RequestType.COMMAND : RequestType.ACTION;
this.commandName = actionRequest.isCommand() ? actionRequest.getCommandName() : actionRequest.getActionName();
}
}
@AssistedInject
/**
* Load existing request from database
*/
public Request(@Assisted RequestEntity entity, StageFactory stageFactory){
if (entity == null) {
throw new RuntimeException("Request entity cannot be null.");
}
this.requestId = entity.getRequestId();
this.clusterId = entity.getCluster().getClusterId();
this.clusterName = entity.getCluster().getClusterName();
this.createTime = entity.getCreateTime();
this.startTime = entity.getStartTime();
this.endTime = entity.getEndTime();
this.requestContext = entity.getRequestContext();
this.inputs = entity.getInputs();
this.targetService = entity.getTargetService();
this.targetComponent = entity.getTargetComponent();
this.targetHosts = entity.getTargetHosts();
this.requestType = entity.getRequestType();
this.commandName = entity.getCommandName();
- this.requestScheduleId = entity.getRequestScheduleEntity().getScheduleId();
+ if (entity.getRequestScheduleEntity() !=null) {
+ this.requestScheduleId = entity.getRequestScheduleEntity().getScheduleId();
+ }
for (StageEntity stageEntity : entity.getStages()) {
Stage stage = stageFactory.createExisting(stageEntity);
stages.add(stage);
}
}
public Collection<Stage> getStages() {
return stages;
}
public void setStages(Collection<Stage> stages) {
this.stages = stages;
}
public long getRequestId() {
return requestId;
}
public synchronized RequestEntity constructNewPersistenceEntity() {
RequestEntity requestEntity = new RequestEntity();
requestEntity.setRequestId(requestId);
requestEntity.setClusterId(clusterId);
requestEntity.setCreateTime(createTime);
requestEntity.setStartTime(startTime);
requestEntity.setEndTime(endTime);
requestEntity.setRequestContext(requestContext);
requestEntity.setInputs(inputs);
requestEntity.setTargetService(targetService);
requestEntity.setTargetComponent(targetComponent);
requestEntity.setTargetHosts(targetHosts);
requestEntity.setRequestType(requestType);
requestEntity.setRequestScheduleId(requestScheduleId);
//TODO set all fields
return requestEntity;
}
public Long getClusterId() {
return clusterId;
}
public String getClusterName() {
return clusterName;
}
public String getRequestContext() {
return requestContext;
}
public void setRequestContext(String requestContext) {
this.requestContext = requestContext;
}
public long getCreateTime() {
return createTime;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public String getInputs() {
return inputs;
}
public void setInputs(String inputs) {
this.inputs = inputs;
}
public String getTargetService() {
return targetService;
}
public void setTargetService(String targetService) {
this.targetService = targetService;
}
public String getTargetComponent() {
return targetComponent;
}
public void setTargetComponent(String targetComponent) {
this.targetComponent = targetComponent;
}
public String getTargetHosts() {
return targetHosts;
}
public void setTargetHosts(String targetHosts) {
this.targetHosts = targetHosts;
}
public RequestType getRequestType() {
return requestType;
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public Long getRequestScheduleId() {
return requestScheduleId;
}
public void setRequestScheduleId(Long requestScheduleId) {
this.requestScheduleId = requestScheduleId;
}
public List<HostRoleCommand> getCommands() {
List<HostRoleCommand> commands = new ArrayList<HostRoleCommand>();
for (Stage stage : stages) {
commands.addAll(stage.getOrderedHostRoleCommands());
}
return commands;
}
@Override
public String toString() {
return "Request{" +
"requestId=" + requestId +
", clusterId=" + clusterId +
", clusterName='" + clusterName + '\'' +
", requestContext='" + requestContext + '\'' +
", createTime=" + createTime +
", startTime=" + startTime +
", endTime=" + endTime +
", inputs='" + inputs + '\'' +
", targetService='" + targetService + '\'' +
", targetComponent='" + targetComponent + '\'' +
", targetHosts='" + targetHosts + '\'' +
", requestType=" + requestType +
", stages=" + stages +
'}';
}
}
| true | true | public Request(@Assisted RequestEntity entity, StageFactory stageFactory){
if (entity == null) {
throw new RuntimeException("Request entity cannot be null.");
}
this.requestId = entity.getRequestId();
this.clusterId = entity.getCluster().getClusterId();
this.clusterName = entity.getCluster().getClusterName();
this.createTime = entity.getCreateTime();
this.startTime = entity.getStartTime();
this.endTime = entity.getEndTime();
this.requestContext = entity.getRequestContext();
this.inputs = entity.getInputs();
this.targetService = entity.getTargetService();
this.targetComponent = entity.getTargetComponent();
this.targetHosts = entity.getTargetHosts();
this.requestType = entity.getRequestType();
this.commandName = entity.getCommandName();
this.requestScheduleId = entity.getRequestScheduleEntity().getScheduleId();
for (StageEntity stageEntity : entity.getStages()) {
Stage stage = stageFactory.createExisting(stageEntity);
stages.add(stage);
}
}
| public Request(@Assisted RequestEntity entity, StageFactory stageFactory){
if (entity == null) {
throw new RuntimeException("Request entity cannot be null.");
}
this.requestId = entity.getRequestId();
this.clusterId = entity.getCluster().getClusterId();
this.clusterName = entity.getCluster().getClusterName();
this.createTime = entity.getCreateTime();
this.startTime = entity.getStartTime();
this.endTime = entity.getEndTime();
this.requestContext = entity.getRequestContext();
this.inputs = entity.getInputs();
this.targetService = entity.getTargetService();
this.targetComponent = entity.getTargetComponent();
this.targetHosts = entity.getTargetHosts();
this.requestType = entity.getRequestType();
this.commandName = entity.getCommandName();
if (entity.getRequestScheduleEntity() !=null) {
this.requestScheduleId = entity.getRequestScheduleEntity().getScheduleId();
}
for (StageEntity stageEntity : entity.getStages()) {
Stage stage = stageFactory.createExisting(stageEntity);
stages.add(stage);
}
}
|
diff --git a/src/com/leafdigital/browserstats/graph/Graph.java b/src/com/leafdigital/browserstats/graph/Graph.java
index 6565cd0..9e75290 100644
--- a/src/com/leafdigital/browserstats/graph/Graph.java
+++ b/src/com/leafdigital/browserstats/graph/Graph.java
@@ -1,1260 +1,1260 @@
/*
This file is part of leafdigital browserstats.
browserstats 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.
browserstats 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 browserstats. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 Samuel Marshall.
*/
package com.leafdigital.browserstats.graph;
import java.awt.*;
import java.awt.geom.Point2D;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.*;
import com.leafdigital.browserstats.shared.*;
/** Draws a graph based on .summary files. */
public class Graph extends CommandLineTool
{
private boolean overwrite, stdout, png, svg, csv,
startLabels = true, endLabels = true;
private boolean csvPercentage = true;
private Color background = Color.WHITE, foreground = Color.BLACK;
private File folder;
private int width=800, height=600, labelSize = 12, footnoteSize = 9,
titleSize = 18;
private String category, prefix, fontName, title;
/**
* @param args Command-line arguments
*/
public static void main(String[] args)
{
// Set headless in case we're running on a server
System.setProperty("java.awt.headless", "true");
(new Graph()).run(args);
}
@Override
protected int processArg(String[] args, int i)
throws IllegalArgumentException
{
if(args[i].equals("-overwrite"))
{
overwrite = true;
return 1;
}
if(args[i].equals("-folder"))
{
checkArgs(args, i, 1);
folder = new File(args[i+1]);
if(!folder.exists() || !folder.isDirectory())
{
throw new IllegalArgumentException("Folder does not exist: " + folder);
}
return 2;
}
if(args[i].equals("-stdout"))
{
stdout = true;
return 1;
}
if(args[i].equals("-size"))
{
checkArgs(args, i, 2);
try
{
width = Integer.parseInt(args[i+1]);
height = Integer.parseInt(args[i+2]);
}
catch(NumberFormatException e)
{
throw new IllegalArgumentException("Invalid size (format: -size 800 600)");
}
if(width<200 || height < 100 || width > 16000 || height > 16000)
{
throw new IllegalArgumentException("Invalid size (out of range)");
}
return 3;
}
if(args[i].equals("-format"))
{
checkArgs(args, i, 1);
String format = args[i+1];
if(format.equals("png"))
{
png = true;
}
else if(format.equals("svg"))
{
svg = true;
}
else if(format.equals("csv"))
{
csv = true;
}
else
{
throw new IllegalArgumentException("-format unknown: " + format);
}
return 2;
}
if(args[i].equals("-csv"))
{
checkArgs(args, i, 1);
String type = args[i+1];
csv = true;
if(type.equals("percentage"))
{
csvPercentage = true;
}
else if(type.equals("count"))
{
csvPercentage = false;
}
else
{
throw new IllegalArgumentException("-csv unknown: " + csv);
}
return 2;
}
if(args[i].equals("-labels"))
{
checkArgs(args, i, 1);
String labels = args[i+1];
if(labels.equals("both"))
{
startLabels = true;
endLabels = true;
}
else if(labels.equals("none"))
{
startLabels = false;
endLabels = false;
}
else if(labels.equals("start"))
{
startLabels = true;
endLabels = false;
}
else if(labels.equals("end"))
{
startLabels = false;
endLabels = true;
}
else
{
throw new IllegalArgumentException("-labels unknown: " + labels);
}
return 2;
}
if(args[i].equals("-category"))
{
checkArgs(args, i, 1);
category = args[i+1];
return 2;
}
if(args[i].equals("-background"))
{
checkArgs(args, i, 1);
background = ColorUtils.fromString(args[i+1]);
return 2;
}
if(args[i].equals("-foreground"))
{
checkArgs(args, i, 1);
foreground = ColorUtils.fromString(args[i+1]);
return 2;
}
if(args[i].equals("-font"))
{
checkArgs(args, i, 1);
fontName = args[i+1];
boolean ok = false;
for(String available : GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames())
{
if(available.equals(fontName))
{
ok = true;
break;
}
}
if(!ok)
{
throw new IllegalArgumentException("Couldn't find font: " + fontName);
}
return 2;
}
if(args[i].equals("-labelsize"))
{
labelSize = getSizeParameter(args, i);
return 2;
}
if(args[i].equals("-footnotesize"))
{
footnoteSize = getSizeParameter(args, i);
return 2;
}
if(args[i].equals("-titlesize"))
{
titleSize = getSizeParameter(args, i);
return 2;
}
if(args[i].equals("-prefix"))
{
checkArgs(args, i, 1);
prefix = args[i+1];
return 2;
}
if(args[i].equals("-title"))
{
checkArgs(args, i, 1);
title = args[i+1];
return 2;
}
return 0;
}
private int getSizeParameter(String[] args, int i)
throws IllegalArgumentException
{
checkArgs(args, i, 1);
try
{
int size = Integer.parseInt(args[i+1]);
if(size<1 || size > 999)
{
throw new IllegalArgumentException("Size out of range: " + args[i+1]);
}
return size;
}
catch(NumberFormatException e)
{
throw new IllegalArgumentException("Invalid size: " + args[i+1]);
}
}
/** @return True if user is on Mac */
public static boolean isMac()
{
// Code from http://developer.apple.com/technotes/tn2002/tn2110.html
String lcOSName=System.getProperty("os.name").toLowerCase();
return lcOSName.startsWith("mac os x");
}
@Override
protected void validateArgs() throws IllegalArgumentException
{
if(fontName == null)
{
if(isMac())
{
fontName = "Helvetica Neue";
}
else
{
fontName = "sans-serif";
}
}
// If format not specified, default to PNG
if(!(png || svg || csv))
{
png = true;
}
// If stdout or stdin is set, check only one format is specified
if( (stdout || getInputFiles() == null) &&
((csv ? 1 : 0) + (png ? 1 : 0) + (svg ? 1 : 0)) != 1)
{
throw new IllegalArgumentException(
"Cannot write multiple formats to stdout");
}
}
@Override
protected void go()
{
// Process and check input files
LinkedList<InputFile> inputFiles = new LinkedList<InputFile>();
File current = null;
try
{
File[] input = getInputFiles();
if(input == null)
{
inputFiles.add(new InputFile(null, category));
}
else
{
for(File file : input)
{
current = file;
inputFiles.add(new InputFile(file, category));
}
}
}
catch(IOException e)
{
String name = current == null ? "stdin" : current.toString();
System.err.println(name + ": " + e.getMessage());
return;
}
// Set up canvas(es)
Canvas[] canvases = new Canvas[png && svg ? 2 : png || svg ? 1 : 0];
if(png)
{
canvases[0] = new PngCanvas(width, height, background);
}
if(svg)
{
canvases[png ? 1 : 0] = new SvgCanvas(width, height, background);
}
// Store CSV data
String csvData = null;
try
{
// Different paths for one or multiple
InputFile lastInputFile;
if(inputFiles.size() == 1)
{
lastInputFile = inputFiles.getFirst();
updateLastDetails(lastInputFile);
for(Canvas canvas : canvases)
{
pieChart(lastInputFile, canvas);
}
if(csv)
{
csvData = singleCsv(lastInputFile);
}
}
else
{
// Check each file has a date
for(InputFile file : inputFiles)
{
if(file.getDate() == null)
{
throw new IOException(file.getName()
+ ": cannot determine date from filename");
}
}
// Sort files into order
InputFile[] inputFilesSorted =
inputFiles.toArray(new InputFile[inputFiles.size()]);
Arrays.sort(inputFilesSorted);
lastInputFile = inputFilesSorted[inputFilesSorted.length - 1];
updateLastDetails(lastInputFile);
// Do trend chart
for(Canvas canvas : canvases)
{
trendChart(inputFilesSorted, canvas);
}
if(csv)
{
csvData = trendCsv(inputFilesSorted);
}
}
// Save output
if(stdout || getInputFiles() == null)
{
if(canvases.length != 0)
{
System.out.write(canvases[0].save());
}
if(csv)
{
System.out.write(csvData.getBytes("UTF-8"));
}
}
else
{
for(Canvas canvas : canvases)
{
File file = new File(folder, prefix + canvas.getExtension());
if(file.exists() && !overwrite)
{
throw new IOException("File exists (use -overwrite): " + file);
}
FileOutputStream out = new FileOutputStream(file);
out.write(canvas.save());
out.close();
}
if(csv)
{
File file = new File(folder, prefix + ".csv");
if(file.exists() && !overwrite)
{
throw new IOException("File exists (use -overwrite): " + file);
}
FileOutputStream out = new FileOutputStream(file);
out.write(csvData.getBytes("UTF-8"));
out.close();
}
}
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
}
private void updateLastDetails(InputFile lastInputFile)
{
if(prefix == null)
{
prefix = lastInputFile.getName().replaceAll("\\.summary$", "");
}
if(title == null)
{
title = prefix;
}
if(folder == null && lastInputFile.getFile() != null)
{
folder = lastInputFile.getFile().getParentFile();
}
}
private void pieChart(InputFile file, Canvas canvas)
{
// METRICS
//////////
int mTitleBottomPadding = 10, mLegendLeftPadding = 20,
mLegendEntryBottomPadding = 10, mLegendEntryRightPadding = 20,
mLegendRowPadding = 10, mLegendTopPadding = 20,
mSliceLabelPadding = 10;
// LAYOUT
/////////
// Do title and calculate height
double titleSpace = 0;
if(!title.isEmpty())
{
TextDrawable titleLabel = new TextDrawable(title, 0, 0, foreground, fontName, false, titleSize);
titleLabel.setVerticalTop(0);
canvas.add(titleLabel);
titleSpace = titleLabel.getHeight() + mTitleBottomPadding;
}
// Get all group names except excluded, also count total
int total = 0;
String[] allGroupNames = file.getGroupNames();
LinkedList<String> groupNamesList = new LinkedList<String>();
for(String groupName : allGroupNames)
{
if(SpecialNames.GROUP_EXCLUDED.equals(groupName))
{
continue;
}
groupNamesList.add(groupName);
total += file.getCount(groupName);
}
String[] groupNames =
groupNamesList.toArray(new String[groupNamesList.size()]);
// Set up colours
fillGroupColours(groupNames);
// Work out current graph position (before legend)
double graphX = 0, graphY = titleSpace,
graphWidth = canvas.getWidth(), graphHeight = canvas.getHeight() - graphY;
// Work out legend entries
LegendEntry[] legendEntries = new LegendEntry[groupNames.length];
for(int group=0; group<groupNames.length; group++)
{
String groupName = groupNames[group];
GroupColours groupColour = groupColours.get(groupName);
legendEntries[group] = new LegendEntry(group, groupColour.getMain(), groupName,
TrendData.getPercentageString(file.getCount(groupName), total),
fontName, foreground, labelSize);
}
// Draw legend to right or below?
if(graphWidth > graphHeight)
{
// Legend to right
// Get max width
double maxLegendWidth = 0;
for(LegendEntry entry : legendEntries)
{
maxLegendWidth = Math.max(maxLegendWidth, entry.getWidth());
}
// Update metrics
double legendX = graphX + graphWidth - maxLegendWidth;
graphWidth -= maxLegendWidth - mLegendLeftPadding;
// Draw legend entries
double legendY = graphY;
for(LegendEntry entry : legendEntries)
{
entry.move(legendX, legendY);
entry.addTo(canvas);
legendY += entry.getHeight() + mLegendEntryBottomPadding;
}
}
else
{
// Legend below
// First flow to count lines and get max height
double available = graphWidth;
int lines = 1;
double maxHeight = 0;
for(LegendEntry entry : legendEntries)
{
// Note: All heights should be the same really (or it will look silly)
// so this maximum counting is not really necessary, but just in case.
maxHeight = Math.max(maxHeight, entry.getHeight());
available -= entry.getWidth() + mLegendEntryRightPadding;
if(available < 0)
{
lines++;
available = graphWidth - entry.getWidth();
}
}
// Calculate height
double legendHeight = maxHeight * lines + mLegendRowPadding * (lines-1);
graphHeight -= legendHeight + mLegendTopPadding;
// Second flow to actually draw legend
double legendY = graphY + graphHeight + mLegendTopPadding;
double legendX = 0;
for(LegendEntry entry : legendEntries)
{
if(legendX + entry.getWidth() > graphWidth)
{
legendX = 0;
legendY += maxHeight + mLegendRowPadding;
}
entry.move(legendX, legendY);
entry.addTo(canvas);
legendX += entry.getWidth() + mLegendEntryRightPadding;
}
}
// Draw each group
double
middleX = graphX + graphWidth / 2.0,
middleY = graphY + graphHeight / 2.0,
radius = Math.min(graphWidth, graphHeight) / 2.0;
double angle = 0;
List<PieSliceDrawable> sliceList = new LinkedList<PieSliceDrawable>();
List<TextDrawable> labelList = new LinkedList<TextDrawable>();
for(int i=0; i<groupNames.length; i++)
{
// Calculate the pie slice.
String groupName = groupNames[i];
double count = file.getCount(groupName);
double degrees = (count / total) * 360.0;
GroupColours groupColour = groupColours.get(groupName);
PieSliceDrawable slice = new PieSliceDrawable(middleX, middleY, radius,
angle, degrees, groupColour.getMain());
sliceList.add(slice);
// We don't actually draw the slice yet, only the borders for overprinting
if(i == 0)
{
canvas.add(slice.getOverprintRadius(false, 2.0));
}
if(i < groupNames.length - 1)
{
canvas.add(slice.getOverprintRadius(true, 2.0));
}
// Calculate the space for a label
TextDrawable name = new TextDrawable(groupName, 0, 0, groupColour.getText(),
fontName, true, labelSize);
Point2D labelPoint = slice.getLabelPosition(
name.getWidth(), name.getHeight(), mSliceLabelPadding);
if(labelPoint != null)
{
name.move(labelPoint.getX(),
labelPoint.getY() + name.getAscent());
labelList.add(name);
}
angle += degrees;
}
// Now draw the actual slices
for(PieSliceDrawable slice : sliceList)
{
canvas.add(slice);
}
// And draw the labels
for(TextDrawable label : labelList)
{
canvas.add(label);
}
}
private void trendChart(InputFile[] files, Canvas canvas)
{
// Get data
TrendData data = new TrendData(files);
String[] groupNames = data.getGroupNames();
fillGroupColours(data.getGroupNames());
// METRICS
//////////
int mLabelSidePadding = 10, mLargeCurveWidth = 20, mTitleBottomPadding = 10,
mLargeCurvePadding = 10, mFootnoteMargin = 20, mFootnoteVerticalSpacing = 10,
mDateMargin = 20, mDateTopPadding = 5, mLabelVerticalPadding = 4;
double mOverprint = 1;
// LAYOUT
/////////
// Do title and calculate height
TextDrawable titleLabel = new TextDrawable(title, 0, 0, foreground, fontName, false, titleSize);
titleLabel.setVerticalTop(0);
canvas.add(titleLabel);
double titleHeight = titleLabel.getHeight();
double graphY = titleHeight + mTitleBottomPadding;
// Find all end labels and calculate width
LinkedList<Label> endLabelsList = new LinkedList<Label>();
int numPoints = data.getNumPoints();
int lastPoint = numPoints - 1;
double endLabelsWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, lastPoint) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
data.getPercentage(group, lastPoint), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
endLabelsList.add(label);
endLabelsWidth = Math.max(endLabelsWidth, label.getWidth());
}
}
Label[] endLabelsArray =
endLabelsList.toArray(new Label[endLabelsList.size()]);
endLabelsWidth += mLabelSidePadding * 2 + mLargeCurveWidth
+ mLargeCurvePadding;
// Find all start labels and calculate width
LinkedList<Label> startLabelsList = new LinkedList<Label>();
double startLabelsMinWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
- data.getPercentage(group, lastPoint), fontName,
+ data.getPercentage(group, 0), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
startLabelsList.add(label);
startLabelsMinWidth = Math.max(startLabelsMinWidth, label.getWidth());
}
}
Label[] startLabelsArray =
startLabelsList.toArray(new Label[startLabelsList.size()]);
double startLabelsWidth = startLabelsMinWidth + mLabelSidePadding * 2
+ mLargeCurveWidth + mLargeCurvePadding;
double graphX = startLabels ? startLabelsWidth : 0;
// We now know the width of the graph
double graphWidth = canvas.getWidth() - graphX
- (endLabels ? endLabelsWidth : 0);
// Find all footnotes - these are groups which are not present in either
// the start or end of the graph.
int footnoteNumber = 1;
LinkedList<Footnote> footnotesList = new LinkedList<Footnote>();
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) == 0 && data.getValue(group, lastPoint) == 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Footnote footnote = new Footnote(group,
new TextDrawable(groupNames[group], 0, 0,
foreground, fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize));
footnotesList.add(footnote);
footnoteNumber++;
}
}
// Calculate footnote wrapping.
// Note that line 0 is the date line, we don't put footnotes on there
// now, so it will always be skipped.
double lineAvailable = 0;
double x = 0;
int lineIndex = 0;
double rowHeight = 0;
for(Footnote footnote : footnotesList)
{
if(footnote.getWidth() > lineAvailable)
{
lineIndex++;
x = 0;
lineAvailable = canvas.getWidth() - (endLabels ? endLabelsWidth : 0);
}
footnote.setRoughPosition(x, lineIndex);
double width = footnote.getWidth() + mFootnoteMargin;
x += width;
lineAvailable -= width;
if(rowHeight == 0)
{
rowHeight = footnote.getHeight();
}
}
double footnotesHeight = (rowHeight * (lineIndex+1)) + (lineIndex * mFootnoteVerticalSpacing);
// If there are no footnotes, calculate height using the date row only
TextDrawable[] dateText = new TextDrawable[numPoints];
double dateHeight = 0;
for(int i=0; i<numPoints; i++)
{
dateText[i] = new TextDrawable(data.getPointDate(i), 0, 0,
foreground, fontName, false, footnoteSize);
dateHeight = Math.max(dateHeight, dateText[i].getHeight());
}
// This is the height of the bottom area below the graph
double bottomAreaHeight = Math.max(footnotesHeight, dateHeight);
// And this is the height of the main graph area
double graphHeight = canvas.getHeight() - bottomAreaHeight -
titleHeight - mTitleBottomPadding - mDateTopPadding;
// Work out the main graph positions for each point based on the timeline
int
minDate = data.getPointLinearDateStart(0),
maxDate = data.getPointLinearDateEnd(numPoints - 1);
double dateScale = graphWidth / (double)(maxDate - minDate);
PointPosition[] pointPositions = new PointPosition[numPoints];
for(int i=0; i<pointPositions.length; i++)
{
double start = (data.getPointLinearDateStart(i) - minDate) * dateScale;
double end = (data.getPointLinearDateEnd(i) - minDate) * dateScale;
pointPositions[i] = new PointPosition(start, end,
i == pointPositions.length - 1);
}
// Position last date
double dateY = canvas.getHeight() - bottomAreaHeight;
double dateTextY = dateY + dateText[0].getAscent();
double lastDateWidth = dateText[dateText.length-1].getWidth();
double lastDateMiddle = pointPositions[numPoints-1].getMiddle();
double lastDateX;
if(lastDateMiddle + (lastDateWidth/2) > graphWidth)
{
lastDateX = graphWidth - lastDateWidth;
}
else
{
lastDateX = lastDateMiddle - lastDateWidth/2;
}
dateText[dateText.length-1].move(lastDateX + graphX, dateTextY);
// Position first date, unless it overlaps
double firstDateWidth = dateText[0].getWidth();
double firstDateMiddle = pointPositions[0].getMiddle();
double firstDateX;
if(firstDateMiddle - (firstDateWidth/2) < 0)
{
firstDateX = 0;
}
else
{
firstDateX = firstDateMiddle - firstDateWidth/2;
}
if(firstDateX + firstDateWidth >= lastDateX - mDateMargin)
{
dateText[0] = null;
}
else
{
dateText[0].move(firstDateX + graphX, dateTextY);
}
// Position other dates when there is room
double nextAvailableX = firstDateX + firstDateWidth + mDateMargin;
for(int i=1; i<numPoints-1; i++)
{
double dateWidth = dateText[i].getWidth();
double dateMiddle = pointPositions[i].getMiddle();
double dateX = dateMiddle - (dateWidth/2);
if(dateX > nextAvailableX && dateX + dateWidth < lastDateX - mDateMargin)
{
dateText[i].move(dateX + graphX, dateTextY);
nextAvailableX = dateX + dateWidth + mDateMargin;
}
else
{
dateText[i] = null;
}
}
// Actually draw dates
for(int i=0; i<numPoints; i++)
{
if(dateText[i] != null)
{
canvas.add(dateText[i]);
}
}
// Position, move, and draw labels
if(startLabels)
{
// Position
Label.distributeLabelsVertically(data, 0, mLabelSidePadding, graphY, graphHeight,
startLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<startLabelsArray.length; i++)
{
Label label = startLabelsArray[i];
double aboveY = label.getY();
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(0, aboveY, colour);
double endX = startLabelsMinWidth + mLabelSidePadding*2;
shape.lineTo(endX, aboveY);
shape.flatCurveTo(endX + mLargeCurveWidth, realAboveY);
double belowY = aboveY + label.getAllocatedHeight();
double realBelowY = ((double)data.getValue(label.getGroup(), 0)
* graphHeight / data.getTotal(0)) + realAboveY;
shape.lineTo(endX + mLargeCurveWidth, realBelowY);
shape.flatCurveTo(endX, belowY);
shape.lineTo(0, belowY);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(0, belowY, mOverprint, colour);
line.lineTo(endX, belowY);
line.flatCurveTo(endX + mLargeCurveWidth, realBelowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
if(endLabels)
{
// Position
Label.distributeLabelsVertically(data, numPoints-1,
graphX + graphWidth + mLargeCurvePadding + mLargeCurveWidth +
mLabelSidePadding, 0, canvas.getHeight(), endLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<endLabelsArray.length; i++)
{
Label label = endLabelsArray[i];
double startX = graphX + graphWidth + mLargeCurvePadding;
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(startX, realAboveY, colour);
double aboveY = label.getY();
shape.flatCurveTo(startX + mLargeCurveWidth, aboveY);
shape.lineTo(canvas.getWidth(), aboveY);
double belowY = aboveY + label.getAllocatedHeight();
double overprint = belowY > graphY + graphHeight - mOverprint ? 0 : mOverprint;
shape.lineTo(canvas.getWidth(), belowY + overprint);
shape.lineTo(startX + mLargeCurveWidth, belowY + overprint);
double realBelowY = ((double)data.getValue(label.getGroup(), numPoints-1)
* graphHeight / data.getTotal(numPoints-1)) + realAboveY;
shape.flatCurveTo(startX, realBelowY + overprint);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(startX, realBelowY, mOverprint, colour);
line.flatCurveTo(startX + mLargeCurveWidth, belowY);
line.lineTo(canvas.getWidth(), belowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
// Draw actual graph
for(int group=0; group<data.getNumGroups(); group++)
{
// See if there's a footnote for this group
Footnote footnote = null;
for(Footnote possible : footnotesList)
{
if(possible.getGroup() == group)
{
footnote = possible;
break;
}
}
GraphWorm shape = null;
for(int point=0; point<numPoints; point++)
{
PointPosition position = pointPositions[point];
PointPosition lastPosition = point==0 ? null : pointPositions[point-1];
double total = (double)data.getTotal(point);
double value = (double)data.getValue(group, point);
double above = (double)data.getCumulativeValueBefore(group, point);
double aboveY = (above * graphHeight / total) + graphY;
double belowY = (value * graphHeight / total) + aboveY;
if(value != 0)
{
if(shape == null)
{
Color color = groupColours.get(groupNames[group]).getMain();
shape = new GraphWorm(position.start + graphX, aboveY, belowY,
color, group==data.getNumGroups()-1);
}
// Draw curve from last to this
if(lastPosition != null && lastPosition.hasCurve())
{
shape.makeCurve(position.start + graphX, aboveY, belowY);
}
// Draw straight
shape.makeStraight(
(position.hasCurve()
? position.end - PointPosition.POINT_CURVE_SIZE
: position.end) + graphX,
aboveY, belowY);
}
else if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
// Footnotes
for(Footnote footnote : footnotesList)
{
footnote.addTo(canvas, dateY, rowHeight + mFootnoteVerticalSpacing,
groupNames, groupColours, foreground);
}
}
/**
* Finishes off a graph shape.
* @param canvas Canvas
* @param footnote Footnote to receive position
* @param shape Shape to finish
*/
private void finishShape(Canvas canvas, Footnote footnote,
GraphWorm shape)
{
// Draw shape
shape.addTo(canvas);
// Add footnote
if(footnote != null)
{
footnote.setGraphPosition(shape.getFootnoteX(),
shape.getFootnoteY());
}
}
private String singleCsv(InputFile file)
{
StringBuilder out = new StringBuilder();
if(!title.isEmpty())
{
out.append(title);
out.append("\n\n");
}
out.append(","); // Empty cell
if(csvPercentage)
{
out.append("%\n");
}
else
{
out.append("Count\n");
}
// Get all group names except excluded, also count total
int total = 0;
String[] allGroupNames = file.getGroupNames();
LinkedList<String> groupNamesList = new LinkedList<String>();
for(String groupName : allGroupNames)
{
if(SpecialNames.GROUP_EXCLUDED.equals(groupName))
{
continue;
}
groupNamesList.add(groupName);
total += file.getCount(groupName);
}
String[] groupNames =
groupNamesList.toArray(new String[groupNamesList.size()]);
// Output results for each group
for(String groupName : groupNames)
{
out.append(groupName);
out.append(",");
int count = file.getCount(groupName);
if(csvPercentage)
{
out.append(TrendData.getPercentageString(count, total));
}
else
{
out.append(count);
}
out.append("\n");
}
return out.toString();
}
private String trendCsv(InputFile[] files)
{
StringBuilder out = new StringBuilder();
if(!title.isEmpty())
{
out.append(title);
out.append("\n\n");
}
TrendData data = new TrendData(files);
String[] groupNames = data.getGroupNames();
// Do header row, starting with empty cell
for(int point=0; point<data.getNumPoints(); point++)
{
out.append(',');
out.append(data.getPointDate(point));
}
out.append('\n');
// Do group rows
for(int group=0; group<data.getNumGroups(); group++)
{
out.append(groupNames[group]);
for(int point=0; point<data.getNumPoints(); point++)
{
out.append(',');
int count = data.getValue(group, point);
int total = data.getTotal(point);
if(csvPercentage)
{
out.append(TrendData.getPercentageString(count, total));
}
else
{
out.append(count);
}
}
out.append('\n');
}
return out.toString();
}
private Map<String, GroupColours> groupColours =
new HashMap<String, GroupColours>();
private final static int
COLOUR_SATURATION_MAX = 200, COLOUR_SATURATION_MIN = 35,
COLOUR_LIGHTNESS_BRIGHT = 230, COLOUR_LIGHTNESS_BRIGHT_MIN = 180,
COLOUR_LIGHTNESS_DARK = 60, COLOUR_LIGHTNESS_DARK_MAX = 110,
COLOUR_HUE_STEP = 30;
void fillGroupColours(final String[] groupNames)
{
// Organise into list of similar name
Map<String, List<Integer>> similar = new HashMap<String, List<Integer>>();
for(int group = 0; group < groupNames.length; group++)
{
String base = getNameBase(groupNames[group]);
List<Integer> list = similar.get(base);
if(list == null)
{
list = new LinkedList<Integer>();
similar.put(base, list);
}
list.add(group);
}
// Now go through in original order
int hue = 0;
boolean light = true;
for(int group = 0; group < groupNames.length; group++)
{
String base = getNameBase(groupNames[group]);
List<Integer> list = similar.get(base);
if(list == null)
{
// Already done this group
continue;
}
// If there's only one, colour it normally
if(list.size() == 1)
{
Color colour = ColorUtils.fromHsl(hue, COLOUR_SATURATION_MAX,
light ? COLOUR_LIGHTNESS_BRIGHT : COLOUR_LIGHTNESS_DARK);
if(!groupColours.containsKey(groupNames[group]))
{
groupColours.put(groupNames[group],
new GroupColours(colour, light ? Color.BLACK : Color.WHITE));
}
}
else
{
// Sort list into order
Collections.sort(list, new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2)
{
// Work out double value for each group.
return (int)Math.signum(getGroupNumericOrder(o1, groupNames[o1])
- getGroupNumericOrder(o2, groupNames[o2]));
}
});
// Now assign each colour according to evenly divided-out saturations
for(int i=0; i<list.size(); i++)
{
int targetGroup = list.get(i);
float proportion = (float)i / (float)(list.size()-1);
int saturation = Math.round(COLOUR_SATURATION_MIN +
(COLOUR_SATURATION_MAX - COLOUR_SATURATION_MIN) * proportion);
int lightness;
if(light)
{
lightness = Math.round(COLOUR_LIGHTNESS_BRIGHT_MIN
+ (COLOUR_LIGHTNESS_BRIGHT - COLOUR_LIGHTNESS_BRIGHT_MIN) * (proportion));
}
else
{
lightness = Math.round(COLOUR_LIGHTNESS_DARK
+ (COLOUR_LIGHTNESS_DARK_MAX - COLOUR_LIGHTNESS_DARK) * (1.0f - proportion));
}
Color colour = ColorUtils.fromHsl(hue, saturation, lightness);
if(!groupColours.containsKey(groupNames[targetGroup]))
{
groupColours.put(groupNames[targetGroup],
new GroupColours(colour, light ? Color.BLACK : Color.WHITE));
}
}
}
// Mark it done
similar.remove(base);
// Next colour index
hue += COLOUR_HUE_STEP;
if(hue >= 360)
{
hue -= 360;
}
light = !light;
}
}
private final static Pattern NUMBER_REGEX =
Pattern.compile("[0-9]+(\\.[0-9]+)?");
private static double getGroupNumericOrder(int index, String name)
{
// See if we can find a number (possibly decimal) in the name
Matcher m = NUMBER_REGEX.matcher(name);
if(m.find())
{
double value = Double.parseDouble(m.group());
// Use index as a tie-breaker by subtracting a miniscule proportion of it
return value - 0.0000001 * (double)index;
}
// No number, use negative index (ensures that the first one is brightest)
return -(index+1);
}
/**
* Get base name used for identifying similar groups. This is the name up to
* the first characters that is not a letter or whitespace.
* @param name Full name
* @return Base name
*/
private static String getNameBase(String name)
{
for(int i=0; i<name.length(); i++)
{
char c = name.charAt(i);
if(!(Character.isLetter(c) || Character.isWhitespace(c)))
{
if(i==0)
{
// Don't try to do similarity if the name *starts* with one of these
return name;
}
return name.substring(0, i);
}
}
return name;
}
}
| true | true | private void trendChart(InputFile[] files, Canvas canvas)
{
// Get data
TrendData data = new TrendData(files);
String[] groupNames = data.getGroupNames();
fillGroupColours(data.getGroupNames());
// METRICS
//////////
int mLabelSidePadding = 10, mLargeCurveWidth = 20, mTitleBottomPadding = 10,
mLargeCurvePadding = 10, mFootnoteMargin = 20, mFootnoteVerticalSpacing = 10,
mDateMargin = 20, mDateTopPadding = 5, mLabelVerticalPadding = 4;
double mOverprint = 1;
// LAYOUT
/////////
// Do title and calculate height
TextDrawable titleLabel = new TextDrawable(title, 0, 0, foreground, fontName, false, titleSize);
titleLabel.setVerticalTop(0);
canvas.add(titleLabel);
double titleHeight = titleLabel.getHeight();
double graphY = titleHeight + mTitleBottomPadding;
// Find all end labels and calculate width
LinkedList<Label> endLabelsList = new LinkedList<Label>();
int numPoints = data.getNumPoints();
int lastPoint = numPoints - 1;
double endLabelsWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, lastPoint) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
data.getPercentage(group, lastPoint), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
endLabelsList.add(label);
endLabelsWidth = Math.max(endLabelsWidth, label.getWidth());
}
}
Label[] endLabelsArray =
endLabelsList.toArray(new Label[endLabelsList.size()]);
endLabelsWidth += mLabelSidePadding * 2 + mLargeCurveWidth
+ mLargeCurvePadding;
// Find all start labels and calculate width
LinkedList<Label> startLabelsList = new LinkedList<Label>();
double startLabelsMinWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
data.getPercentage(group, lastPoint), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
startLabelsList.add(label);
startLabelsMinWidth = Math.max(startLabelsMinWidth, label.getWidth());
}
}
Label[] startLabelsArray =
startLabelsList.toArray(new Label[startLabelsList.size()]);
double startLabelsWidth = startLabelsMinWidth + mLabelSidePadding * 2
+ mLargeCurveWidth + mLargeCurvePadding;
double graphX = startLabels ? startLabelsWidth : 0;
// We now know the width of the graph
double graphWidth = canvas.getWidth() - graphX
- (endLabels ? endLabelsWidth : 0);
// Find all footnotes - these are groups which are not present in either
// the start or end of the graph.
int footnoteNumber = 1;
LinkedList<Footnote> footnotesList = new LinkedList<Footnote>();
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) == 0 && data.getValue(group, lastPoint) == 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Footnote footnote = new Footnote(group,
new TextDrawable(groupNames[group], 0, 0,
foreground, fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize));
footnotesList.add(footnote);
footnoteNumber++;
}
}
// Calculate footnote wrapping.
// Note that line 0 is the date line, we don't put footnotes on there
// now, so it will always be skipped.
double lineAvailable = 0;
double x = 0;
int lineIndex = 0;
double rowHeight = 0;
for(Footnote footnote : footnotesList)
{
if(footnote.getWidth() > lineAvailable)
{
lineIndex++;
x = 0;
lineAvailable = canvas.getWidth() - (endLabels ? endLabelsWidth : 0);
}
footnote.setRoughPosition(x, lineIndex);
double width = footnote.getWidth() + mFootnoteMargin;
x += width;
lineAvailable -= width;
if(rowHeight == 0)
{
rowHeight = footnote.getHeight();
}
}
double footnotesHeight = (rowHeight * (lineIndex+1)) + (lineIndex * mFootnoteVerticalSpacing);
// If there are no footnotes, calculate height using the date row only
TextDrawable[] dateText = new TextDrawable[numPoints];
double dateHeight = 0;
for(int i=0; i<numPoints; i++)
{
dateText[i] = new TextDrawable(data.getPointDate(i), 0, 0,
foreground, fontName, false, footnoteSize);
dateHeight = Math.max(dateHeight, dateText[i].getHeight());
}
// This is the height of the bottom area below the graph
double bottomAreaHeight = Math.max(footnotesHeight, dateHeight);
// And this is the height of the main graph area
double graphHeight = canvas.getHeight() - bottomAreaHeight -
titleHeight - mTitleBottomPadding - mDateTopPadding;
// Work out the main graph positions for each point based on the timeline
int
minDate = data.getPointLinearDateStart(0),
maxDate = data.getPointLinearDateEnd(numPoints - 1);
double dateScale = graphWidth / (double)(maxDate - minDate);
PointPosition[] pointPositions = new PointPosition[numPoints];
for(int i=0; i<pointPositions.length; i++)
{
double start = (data.getPointLinearDateStart(i) - minDate) * dateScale;
double end = (data.getPointLinearDateEnd(i) - minDate) * dateScale;
pointPositions[i] = new PointPosition(start, end,
i == pointPositions.length - 1);
}
// Position last date
double dateY = canvas.getHeight() - bottomAreaHeight;
double dateTextY = dateY + dateText[0].getAscent();
double lastDateWidth = dateText[dateText.length-1].getWidth();
double lastDateMiddle = pointPositions[numPoints-1].getMiddle();
double lastDateX;
if(lastDateMiddle + (lastDateWidth/2) > graphWidth)
{
lastDateX = graphWidth - lastDateWidth;
}
else
{
lastDateX = lastDateMiddle - lastDateWidth/2;
}
dateText[dateText.length-1].move(lastDateX + graphX, dateTextY);
// Position first date, unless it overlaps
double firstDateWidth = dateText[0].getWidth();
double firstDateMiddle = pointPositions[0].getMiddle();
double firstDateX;
if(firstDateMiddle - (firstDateWidth/2) < 0)
{
firstDateX = 0;
}
else
{
firstDateX = firstDateMiddle - firstDateWidth/2;
}
if(firstDateX + firstDateWidth >= lastDateX - mDateMargin)
{
dateText[0] = null;
}
else
{
dateText[0].move(firstDateX + graphX, dateTextY);
}
// Position other dates when there is room
double nextAvailableX = firstDateX + firstDateWidth + mDateMargin;
for(int i=1; i<numPoints-1; i++)
{
double dateWidth = dateText[i].getWidth();
double dateMiddle = pointPositions[i].getMiddle();
double dateX = dateMiddle - (dateWidth/2);
if(dateX > nextAvailableX && dateX + dateWidth < lastDateX - mDateMargin)
{
dateText[i].move(dateX + graphX, dateTextY);
nextAvailableX = dateX + dateWidth + mDateMargin;
}
else
{
dateText[i] = null;
}
}
// Actually draw dates
for(int i=0; i<numPoints; i++)
{
if(dateText[i] != null)
{
canvas.add(dateText[i]);
}
}
// Position, move, and draw labels
if(startLabels)
{
// Position
Label.distributeLabelsVertically(data, 0, mLabelSidePadding, graphY, graphHeight,
startLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<startLabelsArray.length; i++)
{
Label label = startLabelsArray[i];
double aboveY = label.getY();
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(0, aboveY, colour);
double endX = startLabelsMinWidth + mLabelSidePadding*2;
shape.lineTo(endX, aboveY);
shape.flatCurveTo(endX + mLargeCurveWidth, realAboveY);
double belowY = aboveY + label.getAllocatedHeight();
double realBelowY = ((double)data.getValue(label.getGroup(), 0)
* graphHeight / data.getTotal(0)) + realAboveY;
shape.lineTo(endX + mLargeCurveWidth, realBelowY);
shape.flatCurveTo(endX, belowY);
shape.lineTo(0, belowY);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(0, belowY, mOverprint, colour);
line.lineTo(endX, belowY);
line.flatCurveTo(endX + mLargeCurveWidth, realBelowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
if(endLabels)
{
// Position
Label.distributeLabelsVertically(data, numPoints-1,
graphX + graphWidth + mLargeCurvePadding + mLargeCurveWidth +
mLabelSidePadding, 0, canvas.getHeight(), endLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<endLabelsArray.length; i++)
{
Label label = endLabelsArray[i];
double startX = graphX + graphWidth + mLargeCurvePadding;
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(startX, realAboveY, colour);
double aboveY = label.getY();
shape.flatCurveTo(startX + mLargeCurveWidth, aboveY);
shape.lineTo(canvas.getWidth(), aboveY);
double belowY = aboveY + label.getAllocatedHeight();
double overprint = belowY > graphY + graphHeight - mOverprint ? 0 : mOverprint;
shape.lineTo(canvas.getWidth(), belowY + overprint);
shape.lineTo(startX + mLargeCurveWidth, belowY + overprint);
double realBelowY = ((double)data.getValue(label.getGroup(), numPoints-1)
* graphHeight / data.getTotal(numPoints-1)) + realAboveY;
shape.flatCurveTo(startX, realBelowY + overprint);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(startX, realBelowY, mOverprint, colour);
line.flatCurveTo(startX + mLargeCurveWidth, belowY);
line.lineTo(canvas.getWidth(), belowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
// Draw actual graph
for(int group=0; group<data.getNumGroups(); group++)
{
// See if there's a footnote for this group
Footnote footnote = null;
for(Footnote possible : footnotesList)
{
if(possible.getGroup() == group)
{
footnote = possible;
break;
}
}
GraphWorm shape = null;
for(int point=0; point<numPoints; point++)
{
PointPosition position = pointPositions[point];
PointPosition lastPosition = point==0 ? null : pointPositions[point-1];
double total = (double)data.getTotal(point);
double value = (double)data.getValue(group, point);
double above = (double)data.getCumulativeValueBefore(group, point);
double aboveY = (above * graphHeight / total) + graphY;
double belowY = (value * graphHeight / total) + aboveY;
if(value != 0)
{
if(shape == null)
{
Color color = groupColours.get(groupNames[group]).getMain();
shape = new GraphWorm(position.start + graphX, aboveY, belowY,
color, group==data.getNumGroups()-1);
}
// Draw curve from last to this
if(lastPosition != null && lastPosition.hasCurve())
{
shape.makeCurve(position.start + graphX, aboveY, belowY);
}
// Draw straight
shape.makeStraight(
(position.hasCurve()
? position.end - PointPosition.POINT_CURVE_SIZE
: position.end) + graphX,
aboveY, belowY);
}
else if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
// Footnotes
for(Footnote footnote : footnotesList)
{
footnote.addTo(canvas, dateY, rowHeight + mFootnoteVerticalSpacing,
groupNames, groupColours, foreground);
}
}
| private void trendChart(InputFile[] files, Canvas canvas)
{
// Get data
TrendData data = new TrendData(files);
String[] groupNames = data.getGroupNames();
fillGroupColours(data.getGroupNames());
// METRICS
//////////
int mLabelSidePadding = 10, mLargeCurveWidth = 20, mTitleBottomPadding = 10,
mLargeCurvePadding = 10, mFootnoteMargin = 20, mFootnoteVerticalSpacing = 10,
mDateMargin = 20, mDateTopPadding = 5, mLabelVerticalPadding = 4;
double mOverprint = 1;
// LAYOUT
/////////
// Do title and calculate height
TextDrawable titleLabel = new TextDrawable(title, 0, 0, foreground, fontName, false, titleSize);
titleLabel.setVerticalTop(0);
canvas.add(titleLabel);
double titleHeight = titleLabel.getHeight();
double graphY = titleHeight + mTitleBottomPadding;
// Find all end labels and calculate width
LinkedList<Label> endLabelsList = new LinkedList<Label>();
int numPoints = data.getNumPoints();
int lastPoint = numPoints - 1;
double endLabelsWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, lastPoint) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
data.getPercentage(group, lastPoint), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
endLabelsList.add(label);
endLabelsWidth = Math.max(endLabelsWidth, label.getWidth());
}
}
Label[] endLabelsArray =
endLabelsList.toArray(new Label[endLabelsList.size()]);
endLabelsWidth += mLabelSidePadding * 2 + mLargeCurveWidth
+ mLargeCurvePadding;
// Find all start labels and calculate width
LinkedList<Label> startLabelsList = new LinkedList<Label>();
double startLabelsMinWidth = 0;
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) > 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Label label = new Label(group, groupNames[group],
data.getPercentage(group, 0), fontName,
colours.getText(), labelSize, mLabelVerticalPadding);
startLabelsList.add(label);
startLabelsMinWidth = Math.max(startLabelsMinWidth, label.getWidth());
}
}
Label[] startLabelsArray =
startLabelsList.toArray(new Label[startLabelsList.size()]);
double startLabelsWidth = startLabelsMinWidth + mLabelSidePadding * 2
+ mLargeCurveWidth + mLargeCurvePadding;
double graphX = startLabels ? startLabelsWidth : 0;
// We now know the width of the graph
double graphWidth = canvas.getWidth() - graphX
- (endLabels ? endLabelsWidth : 0);
// Find all footnotes - these are groups which are not present in either
// the start or end of the graph.
int footnoteNumber = 1;
LinkedList<Footnote> footnotesList = new LinkedList<Footnote>();
for(int group=0; group<data.getNumGroups(); group++)
{
if(data.getValue(group, 0) == 0 && data.getValue(group, lastPoint) == 0)
{
GroupColours colours = groupColours.get(groupNames[group]);
Footnote footnote = new Footnote(group,
new TextDrawable(groupNames[group], 0, 0,
foreground, fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize),
new TextDrawable(footnoteNumber + "", 0, 0,
colours.getText(), fontName, false, footnoteSize));
footnotesList.add(footnote);
footnoteNumber++;
}
}
// Calculate footnote wrapping.
// Note that line 0 is the date line, we don't put footnotes on there
// now, so it will always be skipped.
double lineAvailable = 0;
double x = 0;
int lineIndex = 0;
double rowHeight = 0;
for(Footnote footnote : footnotesList)
{
if(footnote.getWidth() > lineAvailable)
{
lineIndex++;
x = 0;
lineAvailable = canvas.getWidth() - (endLabels ? endLabelsWidth : 0);
}
footnote.setRoughPosition(x, lineIndex);
double width = footnote.getWidth() + mFootnoteMargin;
x += width;
lineAvailable -= width;
if(rowHeight == 0)
{
rowHeight = footnote.getHeight();
}
}
double footnotesHeight = (rowHeight * (lineIndex+1)) + (lineIndex * mFootnoteVerticalSpacing);
// If there are no footnotes, calculate height using the date row only
TextDrawable[] dateText = new TextDrawable[numPoints];
double dateHeight = 0;
for(int i=0; i<numPoints; i++)
{
dateText[i] = new TextDrawable(data.getPointDate(i), 0, 0,
foreground, fontName, false, footnoteSize);
dateHeight = Math.max(dateHeight, dateText[i].getHeight());
}
// This is the height of the bottom area below the graph
double bottomAreaHeight = Math.max(footnotesHeight, dateHeight);
// And this is the height of the main graph area
double graphHeight = canvas.getHeight() - bottomAreaHeight -
titleHeight - mTitleBottomPadding - mDateTopPadding;
// Work out the main graph positions for each point based on the timeline
int
minDate = data.getPointLinearDateStart(0),
maxDate = data.getPointLinearDateEnd(numPoints - 1);
double dateScale = graphWidth / (double)(maxDate - minDate);
PointPosition[] pointPositions = new PointPosition[numPoints];
for(int i=0; i<pointPositions.length; i++)
{
double start = (data.getPointLinearDateStart(i) - minDate) * dateScale;
double end = (data.getPointLinearDateEnd(i) - minDate) * dateScale;
pointPositions[i] = new PointPosition(start, end,
i == pointPositions.length - 1);
}
// Position last date
double dateY = canvas.getHeight() - bottomAreaHeight;
double dateTextY = dateY + dateText[0].getAscent();
double lastDateWidth = dateText[dateText.length-1].getWidth();
double lastDateMiddle = pointPositions[numPoints-1].getMiddle();
double lastDateX;
if(lastDateMiddle + (lastDateWidth/2) > graphWidth)
{
lastDateX = graphWidth - lastDateWidth;
}
else
{
lastDateX = lastDateMiddle - lastDateWidth/2;
}
dateText[dateText.length-1].move(lastDateX + graphX, dateTextY);
// Position first date, unless it overlaps
double firstDateWidth = dateText[0].getWidth();
double firstDateMiddle = pointPositions[0].getMiddle();
double firstDateX;
if(firstDateMiddle - (firstDateWidth/2) < 0)
{
firstDateX = 0;
}
else
{
firstDateX = firstDateMiddle - firstDateWidth/2;
}
if(firstDateX + firstDateWidth >= lastDateX - mDateMargin)
{
dateText[0] = null;
}
else
{
dateText[0].move(firstDateX + graphX, dateTextY);
}
// Position other dates when there is room
double nextAvailableX = firstDateX + firstDateWidth + mDateMargin;
for(int i=1; i<numPoints-1; i++)
{
double dateWidth = dateText[i].getWidth();
double dateMiddle = pointPositions[i].getMiddle();
double dateX = dateMiddle - (dateWidth/2);
if(dateX > nextAvailableX && dateX + dateWidth < lastDateX - mDateMargin)
{
dateText[i].move(dateX + graphX, dateTextY);
nextAvailableX = dateX + dateWidth + mDateMargin;
}
else
{
dateText[i] = null;
}
}
// Actually draw dates
for(int i=0; i<numPoints; i++)
{
if(dateText[i] != null)
{
canvas.add(dateText[i]);
}
}
// Position, move, and draw labels
if(startLabels)
{
// Position
Label.distributeLabelsVertically(data, 0, mLabelSidePadding, graphY, graphHeight,
startLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<startLabelsArray.length; i++)
{
Label label = startLabelsArray[i];
double aboveY = label.getY();
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(0, aboveY, colour);
double endX = startLabelsMinWidth + mLabelSidePadding*2;
shape.lineTo(endX, aboveY);
shape.flatCurveTo(endX + mLargeCurveWidth, realAboveY);
double belowY = aboveY + label.getAllocatedHeight();
double realBelowY = ((double)data.getValue(label.getGroup(), 0)
* graphHeight / data.getTotal(0)) + realAboveY;
shape.lineTo(endX + mLargeCurveWidth, realBelowY);
shape.flatCurveTo(endX, belowY);
shape.lineTo(0, belowY);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(0, belowY, mOverprint, colour);
line.lineTo(endX, belowY);
line.flatCurveTo(endX + mLargeCurveWidth, realBelowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
if(endLabels)
{
// Position
Label.distributeLabelsVertically(data, numPoints-1,
graphX + graphWidth + mLargeCurvePadding + mLargeCurveWidth +
mLabelSidePadding, 0, canvas.getHeight(), endLabelsArray);
// Draw
double realAboveY = graphY;
for(int i=0; i<endLabelsArray.length; i++)
{
Label label = endLabelsArray[i];
double startX = graphX + graphWidth + mLargeCurvePadding;
Color colour = groupColours.get(groupNames[label.getGroup()]).getMain();
// Shape in background
ShapeDrawable shape = new ShapeDrawable(startX, realAboveY, colour);
double aboveY = label.getY();
shape.flatCurveTo(startX + mLargeCurveWidth, aboveY);
shape.lineTo(canvas.getWidth(), aboveY);
double belowY = aboveY + label.getAllocatedHeight();
double overprint = belowY > graphY + graphHeight - mOverprint ? 0 : mOverprint;
shape.lineTo(canvas.getWidth(), belowY + overprint);
shape.lineTo(startX + mLargeCurveWidth, belowY + overprint);
double realBelowY = ((double)data.getValue(label.getGroup(), numPoints-1)
* graphHeight / data.getTotal(numPoints-1)) + realAboveY;
shape.flatCurveTo(startX, realBelowY + overprint);
shape.finish();
canvas.add(shape);
// Line to overprint bottom
if(i != startLabelsArray.length-1)
{
LineDrawable line = new LineDrawable(startX, realBelowY, mOverprint, colour);
line.flatCurveTo(startX + mLargeCurveWidth, belowY);
line.lineTo(canvas.getWidth(), belowY);
line.finish();
canvas.add(line);
}
// Label
label.addTo(canvas);
realAboveY = realBelowY;
}
}
// Draw actual graph
for(int group=0; group<data.getNumGroups(); group++)
{
// See if there's a footnote for this group
Footnote footnote = null;
for(Footnote possible : footnotesList)
{
if(possible.getGroup() == group)
{
footnote = possible;
break;
}
}
GraphWorm shape = null;
for(int point=0; point<numPoints; point++)
{
PointPosition position = pointPositions[point];
PointPosition lastPosition = point==0 ? null : pointPositions[point-1];
double total = (double)data.getTotal(point);
double value = (double)data.getValue(group, point);
double above = (double)data.getCumulativeValueBefore(group, point);
double aboveY = (above * graphHeight / total) + graphY;
double belowY = (value * graphHeight / total) + aboveY;
if(value != 0)
{
if(shape == null)
{
Color color = groupColours.get(groupNames[group]).getMain();
shape = new GraphWorm(position.start + graphX, aboveY, belowY,
color, group==data.getNumGroups()-1);
}
// Draw curve from last to this
if(lastPosition != null && lastPosition.hasCurve())
{
shape.makeCurve(position.start + graphX, aboveY, belowY);
}
// Draw straight
shape.makeStraight(
(position.hasCurve()
? position.end - PointPosition.POINT_CURVE_SIZE
: position.end) + graphX,
aboveY, belowY);
}
else if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
if(shape != null)
{
finishShape(canvas, footnote, shape);
shape = null;
}
}
// Footnotes
for(Footnote footnote : footnotesList)
{
footnote.addTo(canvas, dateY, rowHeight + mFootnoteVerticalSpacing,
groupNames, groupColours, foreground);
}
}
|
diff --git a/rameses-client-ui/src/com/rameses/rcp/common/Node.java b/rameses-client-ui/src/com/rameses/rcp/common/Node.java
index a660645f..7fe4af72 100644
--- a/rameses-client-ui/src/com/rameses/rcp/common/Node.java
+++ b/rameses-client-ui/src/com/rameses/rcp/common/Node.java
@@ -1,252 +1,252 @@
/*
* Node.java
*
* Created on January 10, 2010, 7:29 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.rameses.rcp.common;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author elmo
*/
public class Node
{
private Object item;
private String id = "NODE" + new UID();
private String caption;
private String tooltip;
private String mnemonic;
private String icon;
private boolean dynamic;
private boolean leaf;
private boolean loaded;
private List<NodeListener> listeners = new ArrayList();
private Map properties = new HashMap();
private Node.Provider provider;
private Node parent;
public Node() {
this(null, null, null);
}
public Node(String id) {
this(id, null, null);
}
public Node(String id, String caption) {
this(id, caption, null);
}
public Node(String id, String caption, Object item)
{
this.id = resolveId(id);
this.caption = caption;
this.item = item;
}
public Node(Map props) {
if (props == null || props.isEmpty())
throw new NullPointerException("props parameter is required in the Node object");
properties.putAll(props);
this.item = props;
this.id = resolveId(properties.remove("id"));
this.caption = removeString(properties, "caption");
this.mnemonic = removeString(properties, "mnemonic");
this.tooltip = removeString(properties, "tooltip");
this.icon = removeString(properties, "icon");
this.dynamic = "true".equals(removeString(properties,"dynamic"));
Object value = properties.get("folder");
- this.leaf = (value == null? false: !"true".equals(value.toString()));
+ if (value != null && "false".equals(value.toString())) this.leaf = true;
String sleaf = removeString(properties,"leaf");
if (sleaf != null && "true".equals(sleaf)) this.leaf = true;
}
// <editor-fold defaultstate="collapsed" desc=" Getters/Setters ">
public String getId() { return id; }
public void setId(String id) {
this.id = (id == null? "NODE"+new UID(): id);
}
public String getCaption() {
return (caption == null? id: caption);
}
public void setCaption(String caption) {
this.caption = caption;
}
public Object getItem() { return item; }
public void setItem(Object item) {
this.item = item;
}
public String getMnemonic() { return mnemonic; }
public void setMnemonic(String mnemonic) {
this.mnemonic = mnemonic;
}
public String getTooltip() { return tooltip; }
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
public boolean isDynamic() { return dynamic; }
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
public boolean isLeaf() { return leaf; }
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getIcon() { return icon; }
public void setIcon(String icon) { this.icon = icon; }
public boolean isLoaded() { return loaded; }
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public Map getProperties() { return properties; }
public void setProperties(Map properties) {
this.properties = properties;
}
public Node getParent() { return parent; }
public void setParent(Node parent) { this.parent = parent; }
public Node.Provider getProvider() { return provider; }
public void setProvider(Node.Provider provider) {
this.provider = provider;
}
public String getPropertyString(String name) {
Object o = getProperties().get(name);
return (o == null? null: o.toString());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" helper methods ">
private String resolveId(Object id) {
return (id == null? "NODE"+new UID(): id.toString());
}
private String getString(Map props, String name) {
Object value = props.get(name);
return (value == null? null: value.toString());
}
private String removeString(Map props, String name) {
Object value = props.remove(name);
return (value == null? null: value.toString());
}
private int removeInt(Map props, String name) {
try {
return Integer.parseInt(props.get(name).toString());
} catch(Throwable t) {
return -1;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" events handling ">
public void addListener(NodeListener listener)
{
if (listener != null && !listeners.contains(listener))
listeners.add(listener);
}
public void removeListener(NodeListener listener)
{
if (listener != null) listeners.remove(listener);
}
public void reload()
{
for (NodeListener nl: listeners) {
nl.reload();
}
}
protected void finalize() throws Throwable {
super.finalize();
properties.clear();
properties = null;
listeners.clear();
listeners = null;
item = null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" proxying Provider methods ">
public int getIndex() {
Node.Provider provider = getProvider();
return (provider == null? -1: provider.getIndex());
}
public boolean hasItems() {
Node.Provider provider = getProvider();
return (provider == null? false: provider.hasItems());
}
public void reloadItems() {
Node.Provider provider = getProvider();
if (provider != null) provider.reloadItems();
}
public List<Node> getItems() {
Node.Provider provider = getProvider();
return (provider == null? null: provider.getItems());
}
public void select() {
Node.Provider provider = getProvider();
if (provider != null) provider.select();
}
public Object open() {
Node.Provider provider = getProvider();
return (provider == null? null: provider.open());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" Provider interface for additional information ">
public static interface Provider
{
int getIndex();
boolean hasItems();
void reloadItems();
List<Node> getItems();
void select();
Object open();
}
// </editor-fold>
}
| true | true | public Node(Map props) {
if (props == null || props.isEmpty())
throw new NullPointerException("props parameter is required in the Node object");
properties.putAll(props);
this.item = props;
this.id = resolveId(properties.remove("id"));
this.caption = removeString(properties, "caption");
this.mnemonic = removeString(properties, "mnemonic");
this.tooltip = removeString(properties, "tooltip");
this.icon = removeString(properties, "icon");
this.dynamic = "true".equals(removeString(properties,"dynamic"));
Object value = properties.get("folder");
this.leaf = (value == null? false: !"true".equals(value.toString()));
String sleaf = removeString(properties,"leaf");
if (sleaf != null && "true".equals(sleaf)) this.leaf = true;
}
| public Node(Map props) {
if (props == null || props.isEmpty())
throw new NullPointerException("props parameter is required in the Node object");
properties.putAll(props);
this.item = props;
this.id = resolveId(properties.remove("id"));
this.caption = removeString(properties, "caption");
this.mnemonic = removeString(properties, "mnemonic");
this.tooltip = removeString(properties, "tooltip");
this.icon = removeString(properties, "icon");
this.dynamic = "true".equals(removeString(properties,"dynamic"));
Object value = properties.get("folder");
if (value != null && "false".equals(value.toString())) this.leaf = true;
String sleaf = removeString(properties,"leaf");
if (sleaf != null && "true".equals(sleaf)) this.leaf = true;
}
|
diff --git a/src/net/sourceforge/mxupdate/update/userinterface/Inquiry_mxJPO.java b/src/net/sourceforge/mxupdate/update/userinterface/Inquiry_mxJPO.java
index c7f657ec..abeba770 100644
--- a/src/net/sourceforge/mxupdate/update/userinterface/Inquiry_mxJPO.java
+++ b/src/net/sourceforge/mxupdate/update/userinterface/Inquiry_mxJPO.java
@@ -1,205 +1,206 @@
/*
* Copyright 2008-2009 The MxUpdate 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package net.sourceforge.mxupdate.update.userinterface;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import matrix.db.Context;
import net.sourceforge.mxupdate.update.AbstractAdminObject_mxJPO;
import net.sourceforge.mxupdate.update.util.InfoAnno_mxJPO;
import net.sourceforge.mxupdate.util.Mapping_mxJPO.AdminTypeDef;
import static net.sourceforge.mxupdate.update.util.StringUtil_mxJPO.convertTcl;
/**
*
* @author tmoxter
* @version $Id$
*/
@InfoAnno_mxJPO(adminType = AdminTypeDef.Inquiry)
public class Inquiry_mxJPO
extends AbstractAdminObject_mxJPO
{
/**
* Defines the serialize version unique identifier.
*/
private static final long serialVersionUID = -6884861954912987897L;
/**
* Separator used between the inquiry update statements and the inquiry
* code itself.
*/
private final static String INQUIRY_SEPARATOR
= "################################################################################\n"
+ "# INQUIRY CODE #\n"
+ "################################################################################";
/**
* Code for the inquiry.
*/
private String code = null;
/**
* Format for the inquiry.
*/
private String format = null;
/**
* Pattern for the inquiry.
*/
private String pattern = null;
@Override
protected void parse(final String _url,
final String _content)
{
if ("/code".equals(_url)) {
this.code = _content;
} else if ("/fmt".equals(_url)) {
this.format = _content;
} else if ("/pattern".equals(_url)) {
this.pattern = _content;
} else {
super.parse(_url, _content);
}
}
@Override
protected void writeObject(Writer _out) throws IOException
{
_out.append(" \\\n pattern \"").append(convertTcl(this.pattern)).append("\"")
.append(" \\\n format \"").append(convertTcl(this.format)).append("\"")
.append(" \\\n file \"${FILE}\"");
for (final AbstractAdminObject_mxJPO.Property prop : this.getPropertiesMap().values()) {
if (prop.getName().startsWith("%")) {
_out.append(" \\\n add argument \"").append(convertTcl(prop.getName().substring(1))).append("\"")
.append(" \"").append(convertTcl(prop.getValue())).append("\"");
}
}
}
@Override
protected void writeEnd(final Writer _out)
throws IOException
{
_out.append("\n\n# do not change the next three lines, they are needed as separator information:\n")
.append(INQUIRY_SEPARATOR)
.append("\n\n").append(this.code);
}
/**
* Updates this inquiry. Because the TCL source code of an inquiry includes
* also the inquiry code itself, this inquiry code must be separated and
* written in a temporary file. This temporary file is used while the
* update is running (defined via TCL variable <code>FILE</code>). After
* the update, the temporary file is removed (because not needed anymore).
* Also the MQL statements to reset this inquiry are appended to the
* statements in <code>_preMQLCode</code> to:
* <ul>
* <li>reset the description, pattern and code</li>
* <li>remove all arguments</li>
* </ul>
*
* @param _context context for this request
* @param _preMQLCode MQL statements which must be called before the
* TCL code is executed
* @param _postMQLCode MQL statements which must be called after the
* TCL code is executed
* @param _preTCLCode TCL code which is defined before the source
* file is sourced
* @param _tclVariables map of all TCL variables where the key is the
* name and the value is value of the TCL variable
* (the value is automatically converted to TCL
* syntax!)
* @param _sourceFile souce file with the TCL code to update
* @throws Exception if update failed
*/
@Override
protected void update(final Context _context,
final CharSequence _preMQLCode,
final CharSequence _postMQLCode,
final CharSequence _preTCLCode,
final Map<String,String> _tclVariables,
final File _sourceFile)
throws Exception
{
// reset HRef, description, alt, label and height
final StringBuilder preMQLCode = new StringBuilder()
.append("mod ").append(this.getInfoAnno().adminType().getMxName())
.append(" \"").append(this.getName()).append('\"')
.append(" description \"\" pattern \"\" code \"\"");
// reset arguments
for (final AbstractAdminObject_mxJPO.Property prop : this.getPropertiesMap().values()) {
if (prop.getName().startsWith("%")) {
preMQLCode.append(" remove argument \"").append(prop.getName().substring(1)).append('\"');
}
}
// append already existing pre MQL code
preMQLCode.append(";\n")
.append(_preMQLCode);
// separate the inquiry code and the TCL code
- final int idx = this.getCode(_sourceFile).lastIndexOf(INQUIRY_SEPARATOR);
+ final StringBuilder orgCode = this.getCode(_sourceFile);
+ final int idx = orgCode.lastIndexOf(INQUIRY_SEPARATOR);
final CharSequence code = (idx >= 0)
- ? _preTCLCode.subSequence(0, idx)
- : _preTCLCode;
+ ? orgCode.subSequence(0, idx)
+ : orgCode;
final CharSequence inqu = (idx >= 0)
- ? _preTCLCode.subSequence(idx + INQUIRY_SEPARATOR.length() + 1, _preTCLCode.length())
+ ? orgCode.subSequence(idx + INQUIRY_SEPARATOR.length() + 1, orgCode.length())
: "";
final File tmpInqFile = File.createTempFile("TMP_", ".inquiry");
final File tmpTclFile = File.createTempFile("TMP_", ".tcl");
try {
// write TCL code
final Writer outTCL = new FileWriter(tmpTclFile);
outTCL.append(code.toString().trim());
outTCL.flush();
outTCL.close();
// write inquiry code
final Writer outInq = new FileWriter(tmpInqFile);
outInq.append(inqu.toString().trim());
outInq.flush();
outInq.close();
// define TCL variable for the file
final Map<String,String> tclVariables = new HashMap<String,String>();
tclVariables.putAll(_tclVariables);
tclVariables.put("FILE", tmpInqFile.getPath());
// and update
super.update(_context, preMQLCode, _postMQLCode, code, tclVariables, tmpTclFile);
} finally {
tmpInqFile.delete();
tmpTclFile.delete();
}
}
}
| false | true | protected void update(final Context _context,
final CharSequence _preMQLCode,
final CharSequence _postMQLCode,
final CharSequence _preTCLCode,
final Map<String,String> _tclVariables,
final File _sourceFile)
throws Exception
{
// reset HRef, description, alt, label and height
final StringBuilder preMQLCode = new StringBuilder()
.append("mod ").append(this.getInfoAnno().adminType().getMxName())
.append(" \"").append(this.getName()).append('\"')
.append(" description \"\" pattern \"\" code \"\"");
// reset arguments
for (final AbstractAdminObject_mxJPO.Property prop : this.getPropertiesMap().values()) {
if (prop.getName().startsWith("%")) {
preMQLCode.append(" remove argument \"").append(prop.getName().substring(1)).append('\"');
}
}
// append already existing pre MQL code
preMQLCode.append(";\n")
.append(_preMQLCode);
// separate the inquiry code and the TCL code
final int idx = this.getCode(_sourceFile).lastIndexOf(INQUIRY_SEPARATOR);
final CharSequence code = (idx >= 0)
? _preTCLCode.subSequence(0, idx)
: _preTCLCode;
final CharSequence inqu = (idx >= 0)
? _preTCLCode.subSequence(idx + INQUIRY_SEPARATOR.length() + 1, _preTCLCode.length())
: "";
final File tmpInqFile = File.createTempFile("TMP_", ".inquiry");
final File tmpTclFile = File.createTempFile("TMP_", ".tcl");
try {
// write TCL code
final Writer outTCL = new FileWriter(tmpTclFile);
outTCL.append(code.toString().trim());
outTCL.flush();
outTCL.close();
// write inquiry code
final Writer outInq = new FileWriter(tmpInqFile);
outInq.append(inqu.toString().trim());
outInq.flush();
outInq.close();
// define TCL variable for the file
final Map<String,String> tclVariables = new HashMap<String,String>();
tclVariables.putAll(_tclVariables);
tclVariables.put("FILE", tmpInqFile.getPath());
// and update
super.update(_context, preMQLCode, _postMQLCode, code, tclVariables, tmpTclFile);
} finally {
tmpInqFile.delete();
tmpTclFile.delete();
}
}
| protected void update(final Context _context,
final CharSequence _preMQLCode,
final CharSequence _postMQLCode,
final CharSequence _preTCLCode,
final Map<String,String> _tclVariables,
final File _sourceFile)
throws Exception
{
// reset HRef, description, alt, label and height
final StringBuilder preMQLCode = new StringBuilder()
.append("mod ").append(this.getInfoAnno().adminType().getMxName())
.append(" \"").append(this.getName()).append('\"')
.append(" description \"\" pattern \"\" code \"\"");
// reset arguments
for (final AbstractAdminObject_mxJPO.Property prop : this.getPropertiesMap().values()) {
if (prop.getName().startsWith("%")) {
preMQLCode.append(" remove argument \"").append(prop.getName().substring(1)).append('\"');
}
}
// append already existing pre MQL code
preMQLCode.append(";\n")
.append(_preMQLCode);
// separate the inquiry code and the TCL code
final StringBuilder orgCode = this.getCode(_sourceFile);
final int idx = orgCode.lastIndexOf(INQUIRY_SEPARATOR);
final CharSequence code = (idx >= 0)
? orgCode.subSequence(0, idx)
: orgCode;
final CharSequence inqu = (idx >= 0)
? orgCode.subSequence(idx + INQUIRY_SEPARATOR.length() + 1, orgCode.length())
: "";
final File tmpInqFile = File.createTempFile("TMP_", ".inquiry");
final File tmpTclFile = File.createTempFile("TMP_", ".tcl");
try {
// write TCL code
final Writer outTCL = new FileWriter(tmpTclFile);
outTCL.append(code.toString().trim());
outTCL.flush();
outTCL.close();
// write inquiry code
final Writer outInq = new FileWriter(tmpInqFile);
outInq.append(inqu.toString().trim());
outInq.flush();
outInq.close();
// define TCL variable for the file
final Map<String,String> tclVariables = new HashMap<String,String>();
tclVariables.putAll(_tclVariables);
tclVariables.put("FILE", tmpInqFile.getPath());
// and update
super.update(_context, preMQLCode, _postMQLCode, code, tclVariables, tmpTclFile);
} finally {
tmpInqFile.delete();
tmpTclFile.delete();
}
}
|
diff --git a/tests/src/test/java/r/PackageArtifactTest.java b/tests/src/test/java/r/PackageArtifactTest.java
index 5134f70..3f039fc 100644
--- a/tests/src/test/java/r/PackageArtifactTest.java
+++ b/tests/src/test/java/r/PackageArtifactTest.java
@@ -1,20 +1,19 @@
package r;
import java.io.IOException;
import org.junit.Test;
import r.lang.Context;
import r.parser.RParser;
public class PackageArtifactTest {
@Test
public void test() throws IOException {
Context context = Context.newTopLevelContext();
context.init();
- RParser.parseSource("library(aspect, verbose=TRUE)\n")
- .evaluate(context, context.getEnvironment());
+ context.evaluate(RParser.parseSource("library(aspect, verbose=TRUE)\n"));
}
}
| true | true | public void test() throws IOException {
Context context = Context.newTopLevelContext();
context.init();
RParser.parseSource("library(aspect, verbose=TRUE)\n")
.evaluate(context, context.getEnvironment());
}
| public void test() throws IOException {
Context context = Context.newTopLevelContext();
context.init();
context.evaluate(RParser.parseSource("library(aspect, verbose=TRUE)\n"));
}
|
diff --git a/src/main/java/Sirius/navigator/ui/tree/SearchResultsTreePanel.java b/src/main/java/Sirius/navigator/ui/tree/SearchResultsTreePanel.java
index 71024dd..89fad83 100644
--- a/src/main/java/Sirius/navigator/ui/tree/SearchResultsTreePanel.java
+++ b/src/main/java/Sirius/navigator/ui/tree/SearchResultsTreePanel.java
@@ -1,316 +1,316 @@
package Sirius.navigator.ui.tree;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import Sirius.navigator.resource.*;
import Sirius.navigator.method.*;
import Sirius.navigator.search.dynamic.profile.QueryResultProfileManager;
import Sirius.navigator.ui.ComponentRegistry;
import Sirius.server.search.store.QueryInfo;
import de.cismet.tools.gui.JPopupMenuButton;
import org.apache.log4j.Logger;
/**
*
* @author pascal
*/
public class SearchResultsTreePanel extends JPanel
{
private final Logger logger;
private final SearchResultsTree searchResultsTree;
private final JToolBar toolBar;
private JButton browseBackButton, browseForwardButton,
removeButton, clearButton,
saveButton;
private JPopupMenuButton saveAllButton;
private JCheckBox showDirectlyInMap;
public SearchResultsTreePanel(SearchResultsTree searchResultsTree)
{
this(searchResultsTree, false);
}
/** Creates a new instance of SearchResultsTreePanel */
public SearchResultsTreePanel(SearchResultsTree searchResultsTree, boolean advancedLayout)
{
super(new BorderLayout());
this.searchResultsTree = searchResultsTree;
this.toolBar = new JToolBar(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.toolbar.name"),//NOI18N
JToolBar.HORIZONTAL) ;
this.toolBar.setRollover(advancedLayout);
this.toolBar.setFloatable(advancedLayout);
this.logger = Logger.getLogger(this.getClass());
this.init();
}
private void init()
{
this.createDefaultButtons();
this.add(toolBar, BorderLayout.SOUTH);
this.add(new JScrollPane(searchResultsTree), BorderLayout.CENTER);
this.setButtonsEnabled();
ButtonEnablingListener buttonEnablingListener = new ButtonEnablingListener();
this.searchResultsTree.addTreeSelectionListener(buttonEnablingListener);
this.searchResultsTree.addPropertyChangeListener("browse", buttonEnablingListener);//NOI18N
this.addComponentListener(new ComponentEventForwarder());
}
private void createDefaultButtons()
{
ResourceManager resources = ResourceManager.getManager();
ActionListener toolBarListener = new ToolBarListener();
browseBackButton = new JButton(resources.getIcon("back24.gif"));//NOI18N
browseBackButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.backButton.tooltip"));//NOI18N
browseBackButton.setActionCommand("back");//NOI18N
browseBackButton.setMargin(new Insets(4,4,4,4));
browseBackButton.addActionListener(toolBarListener);
toolBar.add(browseBackButton);
//toolBar.addSeparator();
browseForwardButton = new JButton(resources.getIcon("forward24.gif"));//NOI18N
browseForwardButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.browseForwardButton.tooltip"));//NOI18N
browseForwardButton.setActionCommand("forward");//NOI18N
browseForwardButton.setMargin(new Insets(4,4,4,4));
browseForwardButton.addActionListener(toolBarListener);
toolBar.add(browseForwardButton);
toolBar.addSeparator();
removeButton = new JButton(resources.getIcon("remove24.gif"));//NOI18N
removeButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.removeButton.tooltip"));//NOI18N
removeButton.setActionCommand("remove");//NOI18N
removeButton.setMargin(new Insets(4,4,4,4));
removeButton.addActionListener(toolBarListener);
toolBar.add(removeButton);
//toolBar.addSeparator();
clearButton = new JButton(resources.getIcon("delete24.gif"));//NOI18N
clearButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.clearButton.tooltip"));//NOI18N
clearButton.setActionCommand("clear");//NOI18N
clearButton.setMargin(new Insets(4,4,4,4));
clearButton.addActionListener(toolBarListener);
toolBar.add(clearButton);
toolBar.addSeparator();
//saveAllButton = new JButton(resources.getIcon("saveall24.gif"));
saveAllButton = new JPopupMenuButton();
saveAllButton.setPopupMenu(new HistoryPopupMenu());
saveAllButton.setIcon(resources.getIcon("saveall24.gif"));//NOI18N
saveAllButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.saveAllButton.tooltip"));//NOI18N
saveAllButton.setActionCommand("saveall");//NOI18N
saveAllButton.setMargin(new Insets(4,4,4,4));
saveAllButton.addActionListener(toolBarListener);
toolBar.add(saveAllButton);
showDirectlyInMap=new JCheckBox();
showDirectlyInMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchResultsTree.setSyncWithMap(showDirectlyInMap.isSelected());
}
});
showDirectlyInMap.setSelected(false);
toolBar.add(showDirectlyInMap);
- JLabel showDirectlyInMapLabel= new JLabel(resources.getIcon("saveall24.gif"));//NOI18N
+ JLabel showDirectlyInMapLabel= new JLabel(resources.getIcon("map.png"));//NOI18N
showDirectlyInMapLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount()>1) {
searchResultsTree.syncWithMap(true);
}
}
});
showDirectlyInMapLabel.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.showDirectInMapLabel.tooltipText"));//NOI18N
toolBar.add(showDirectlyInMapLabel);
}
public void setButtonsEnabled()
{
browseBackButton.setEnabled(searchResultsTree.isBrowseBack());
browseForwardButton.setEnabled(searchResultsTree.isBrowseForward());
removeButton.setEnabled(!searchResultsTree.isEmpty() && searchResultsTree.getSelectedNodeCount() > 0);
clearButton.setEnabled(!searchResultsTree.isEmpty());
// not implemented:
//saveButton.setEnabled(!searchResultsTree.isEmpty() && searchResultsTree.getSelectedNodeCount() > 0);
//saveButton.setEnabled(false);
//saveAllButton.setEnabled(!searchResultsTree.isEmpty());
saveAllButton.setEnabled(true);
}
public JToolBar getToolBar()
{
return this.toolBar;
}
public SearchResultsTree getSearchResultsTree()
{
return this.searchResultsTree;
}
private class ComponentEventForwarder extends ComponentAdapter
{
/** Invoked when the component has been made invisible.
*
*/
public void componentHidden(ComponentEvent e)
{
searchResultsTree.dispatchEvent(e);
}
/** Invoked when the component has been made visible.
*
*/
public void componentShown(ComponentEvent e)
{
searchResultsTree.dispatchEvent(e);
}
}
private class ToolBarListener implements ActionListener
{
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("back"))//NOI18N
{
searchResultsTree.browseBack();
}
else if(e.getActionCommand().equals("forward"))//NOI18N
{
searchResultsTree.browseForward();
}
else if(e.getActionCommand().equals("remove"))//NOI18N
{
searchResultsTree.removeSelectedResultNodes();
}
else if(e.getActionCommand().equals("clear"))//NOI18N
{
searchResultsTree.clear();
}
else if(e.getActionCommand().equals("save"))//NOI18N
{
//logger.warn("command 'save' not implemented");
}
else if(e.getActionCommand().equals("saveall"))//NOI18N
{
MethodManager.getManager().showQueryResultProfileManager();
}
SearchResultsTreePanel.this.setButtonsEnabled();
}
}
private class ButtonEnablingListener implements PropertyChangeListener, TreeSelectionListener
{
/** This method gets called when a bound property is changed.
* @param evt A PropertyChangeEvent object describing the event source
* and the property that has changed.
*
*/
public void propertyChange(PropertyChangeEvent e)
{
SearchResultsTreePanel.this.setButtonsEnabled();
}
/**
* Called whenever the value of the selection changes.
* @param e the event that characterizes the change.
*
*/
public void valueChanged(TreeSelectionEvent e)
{
SearchResultsTreePanel.this.setButtonsEnabled();
}
}
private class HistoryPopupMenu extends JPopupMenu implements PopupMenuListener, ActionListener
{
private QueryResultProfileManager queryResultProfileManager = null;
public HistoryPopupMenu()
{
if(logger.isDebugEnabled())logger.debug("HistoryPopupMenu(): creating new instance");//NOI18N
this.addPopupMenuListener(this);
// ugly workaround
this.add(new JMenuItem("shouldnotseeme"));//NOI18N
}
public void popupMenuCanceled(PopupMenuEvent e)
{
if(logger.isDebugEnabled())logger.debug("popupMenuCanceled()");//NOI18N
// ugly workaround
this.add(new JMenuItem("shouldnotseeme"));//NOI18N
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
if(logger.isDebugEnabled())logger.debug("popupMenuWillBecomeInvisible()");//NOI18N
// ugly workaround
this.add(new JMenuItem("shouldnotseeme"));//NOI18N
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
if(logger.isDebugEnabled())logger.debug("popupMenuWillBecomeVisible(): showing popup meu");//NOI18N
if(this.queryResultProfileManager == null)
{
this.queryResultProfileManager = ComponentRegistry.getRegistry().getQueryResultProfileManager();
}
if(this.queryResultProfileManager.getUserInfos() == null || this.queryResultProfileManager.getUserInfos().length == 0)
{
this.queryResultProfileManager.updateQueryResultProfileManager();
}
this.removeAll();
QueryInfo[] userInfo = this.queryResultProfileManager.getUserInfos();
if(userInfo != null && userInfo.length > 0)
{
for(int i = 0; i < userInfo.length; i++)
{
JMenuItem menuItem = new JMenuItem(userInfo[i].getName());
menuItem.setActionCommand(userInfo[i].getFileName());
menuItem.addActionListener(this);
this.add(menuItem);
}
}
else if(logger.isDebugEnabled())
{
logger.warn("HistoryPopupMenu: no query result profiles found");//NOI18N
}
}
public void actionPerformed (ActionEvent e)
{
if (logger.isInfoEnabled()) {
logger.info("HistoryPopupMenu: loading query result profile '" + e.getActionCommand() + "'");//NOI18N
}
this.queryResultProfileManager.loadSearchResults(e.getActionCommand());
}
}
}
| true | true | private void createDefaultButtons()
{
ResourceManager resources = ResourceManager.getManager();
ActionListener toolBarListener = new ToolBarListener();
browseBackButton = new JButton(resources.getIcon("back24.gif"));//NOI18N
browseBackButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.backButton.tooltip"));//NOI18N
browseBackButton.setActionCommand("back");//NOI18N
browseBackButton.setMargin(new Insets(4,4,4,4));
browseBackButton.addActionListener(toolBarListener);
toolBar.add(browseBackButton);
//toolBar.addSeparator();
browseForwardButton = new JButton(resources.getIcon("forward24.gif"));//NOI18N
browseForwardButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.browseForwardButton.tooltip"));//NOI18N
browseForwardButton.setActionCommand("forward");//NOI18N
browseForwardButton.setMargin(new Insets(4,4,4,4));
browseForwardButton.addActionListener(toolBarListener);
toolBar.add(browseForwardButton);
toolBar.addSeparator();
removeButton = new JButton(resources.getIcon("remove24.gif"));//NOI18N
removeButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.removeButton.tooltip"));//NOI18N
removeButton.setActionCommand("remove");//NOI18N
removeButton.setMargin(new Insets(4,4,4,4));
removeButton.addActionListener(toolBarListener);
toolBar.add(removeButton);
//toolBar.addSeparator();
clearButton = new JButton(resources.getIcon("delete24.gif"));//NOI18N
clearButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.clearButton.tooltip"));//NOI18N
clearButton.setActionCommand("clear");//NOI18N
clearButton.setMargin(new Insets(4,4,4,4));
clearButton.addActionListener(toolBarListener);
toolBar.add(clearButton);
toolBar.addSeparator();
//saveAllButton = new JButton(resources.getIcon("saveall24.gif"));
saveAllButton = new JPopupMenuButton();
saveAllButton.setPopupMenu(new HistoryPopupMenu());
saveAllButton.setIcon(resources.getIcon("saveall24.gif"));//NOI18N
saveAllButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.saveAllButton.tooltip"));//NOI18N
saveAllButton.setActionCommand("saveall");//NOI18N
saveAllButton.setMargin(new Insets(4,4,4,4));
saveAllButton.addActionListener(toolBarListener);
toolBar.add(saveAllButton);
showDirectlyInMap=new JCheckBox();
showDirectlyInMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchResultsTree.setSyncWithMap(showDirectlyInMap.isSelected());
}
});
showDirectlyInMap.setSelected(false);
toolBar.add(showDirectlyInMap);
JLabel showDirectlyInMapLabel= new JLabel(resources.getIcon("saveall24.gif"));//NOI18N
showDirectlyInMapLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount()>1) {
searchResultsTree.syncWithMap(true);
}
}
});
showDirectlyInMapLabel.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.showDirectInMapLabel.tooltipText"));//NOI18N
toolBar.add(showDirectlyInMapLabel);
}
| private void createDefaultButtons()
{
ResourceManager resources = ResourceManager.getManager();
ActionListener toolBarListener = new ToolBarListener();
browseBackButton = new JButton(resources.getIcon("back24.gif"));//NOI18N
browseBackButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.backButton.tooltip"));//NOI18N
browseBackButton.setActionCommand("back");//NOI18N
browseBackButton.setMargin(new Insets(4,4,4,4));
browseBackButton.addActionListener(toolBarListener);
toolBar.add(browseBackButton);
//toolBar.addSeparator();
browseForwardButton = new JButton(resources.getIcon("forward24.gif"));//NOI18N
browseForwardButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.browseForwardButton.tooltip"));//NOI18N
browseForwardButton.setActionCommand("forward");//NOI18N
browseForwardButton.setMargin(new Insets(4,4,4,4));
browseForwardButton.addActionListener(toolBarListener);
toolBar.add(browseForwardButton);
toolBar.addSeparator();
removeButton = new JButton(resources.getIcon("remove24.gif"));//NOI18N
removeButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.removeButton.tooltip"));//NOI18N
removeButton.setActionCommand("remove");//NOI18N
removeButton.setMargin(new Insets(4,4,4,4));
removeButton.addActionListener(toolBarListener);
toolBar.add(removeButton);
//toolBar.addSeparator();
clearButton = new JButton(resources.getIcon("delete24.gif"));//NOI18N
clearButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.clearButton.tooltip"));//NOI18N
clearButton.setActionCommand("clear");//NOI18N
clearButton.setMargin(new Insets(4,4,4,4));
clearButton.addActionListener(toolBarListener);
toolBar.add(clearButton);
toolBar.addSeparator();
//saveAllButton = new JButton(resources.getIcon("saveall24.gif"));
saveAllButton = new JPopupMenuButton();
saveAllButton.setPopupMenu(new HistoryPopupMenu());
saveAllButton.setIcon(resources.getIcon("saveall24.gif"));//NOI18N
saveAllButton.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.saveAllButton.tooltip"));//NOI18N
saveAllButton.setActionCommand("saveall");//NOI18N
saveAllButton.setMargin(new Insets(4,4,4,4));
saveAllButton.addActionListener(toolBarListener);
toolBar.add(saveAllButton);
showDirectlyInMap=new JCheckBox();
showDirectlyInMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchResultsTree.setSyncWithMap(showDirectlyInMap.isSelected());
}
});
showDirectlyInMap.setSelected(false);
toolBar.add(showDirectlyInMap);
JLabel showDirectlyInMapLabel= new JLabel(resources.getIcon("map.png"));//NOI18N
showDirectlyInMapLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount()>1) {
searchResultsTree.syncWithMap(true);
}
}
});
showDirectlyInMapLabel.setToolTipText(org.openide.util.NbBundle.getMessage(SearchResultsTreePanel.class, "SearchResultsTreePanel.showDirectInMapLabel.tooltipText"));//NOI18N
toolBar.add(showDirectlyInMapLabel);
}
|
diff --git a/waterken/remote/src/org/waterken/remote/http/Callee.java b/waterken/remote/src/org/waterken/remote/http/Callee.java
index a49fe411..2b6219f0 100644
--- a/waterken/remote/src/org/waterken/remote/http/Callee.java
+++ b/waterken/remote/src/org/waterken/remote/http/Callee.java
@@ -1,229 +1,229 @@
// 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 java.io.Serializable;
import java.lang.reflect.Type;
import org.joe_e.Struct;
import org.joe_e.array.ByteArray;
import org.joe_e.array.ConstArray;
import org.joe_e.array.PowerlessArray;
import org.joe_e.reflect.Reflection;
import org.ref_send.promise.Eventual;
import org.ref_send.promise.Promise;
import org.ref_send.promise.Unresolved;
import org.waterken.http.Message;
import org.waterken.http.Request;
import org.waterken.http.Response;
import org.waterken.http.Server;
import org.waterken.io.FileType;
import org.waterken.syntax.BadSyntax;
import org.waterken.syntax.Deserializer;
import org.waterken.syntax.json.JSONDeserializer;
import org.waterken.syntax.json.JSONSerializer;
import org.waterken.uri.Header;
/**
* Server-side of the web-key protocol.
*/
/* package */ final class
Callee extends Struct implements Serializable {
static private final long serialVersionUID = 1L;
private final HTTP.Exports exports;
protected
Callee(final HTTP.Exports exports) {
this.exports = exports;
}
static private final Class<?> Fulfilled = Eventual.ref(0).getClass();
protected Message<Response>
apply(final String query, final Message<Request> m) throws Exception {
// further dispatch the request based on the accessed member
final String p = HTTP.predicate(m.head.method, query);
if (null == p) { // when block
if ("OPTIONS".equals(m.head.method)) {
return new Message<Response>(
Response.options("TRACE", "OPTIONS", "GET", "HEAD"), null);
}
if (!("GET".equals(m.head.method) || "HEAD".equals(m.head.method))){
return new Message<Response>(
Response.notAllowed("TRACE","OPTIONS","GET","HEAD"), null);
}
Object value;
try {
// AUDIT: call to untrusted application code
value = Eventual.ref(exports.reference(query)).call();
} catch (final Unresolved e) {
return serialize(m.head.method, "404", "not yet",
Server.ephemeral, Exception.class, e);
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Response failed = m.head.allow("\"\"");
if (null != failed) { return new Message<Response>(failed, null); }
return serialize(m.head.method, "200", "OK", Server.forever,
Object.class, value);
} // member access
// determine the target object
final Object target;
try {
final Promise<?> subject = Eventual.ref(exports.reference(query));
// to preserve message order, only access members on a fulfilled ref
if (!Fulfilled.isInstance(subject)) { throw new Unresolved(); }
target = subject.call();
} catch (final Exception e) {
return serialize(m.head.method, "404", "never", Server.forever,
Exception.class, e);
}
if ("GET".equals(m.head.method) || "HEAD".equals(m.head.method)) {
final Dispatch property = Dispatch.get(target, p);
if (null == property) { // no such property
final boolean post = null != Dispatch.post(target, p);
return new Message<Response>(Response.notAllowed(
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" }), null);
}
Object value; // property access
try {
// AUDIT: call to untrusted application code
final Object r = Reflection.invoke(property.declaration,target);
value = Fulfilled.isInstance(r) ? ((Promise<?>)r).call() : r;
} catch (final Exception e) {
value = Eventual.reject(e);
}
final String etag = exports.getTransactionTag();
final Response failed = m.head.allow(etag);
if (null != failed) { return new Message<Response>(failed, null); }
Message<Response> r = serialize(
m.head.method, "200", "OK", Server.ephemeral,
- property.implementation.getGenericReturnType(), value);
+ property.declaration.getGenericReturnType(), value);
if (null != etag) {
r = new Message<Response>(r.head.with("ETag", etag), r.body);
}
return r;
}
if ("POST".equals(m.head.method)) {
final Response failed = m.head.allow(null);
if (null != failed) { return new Message<Response>(failed, null); }
return exports.execute(query, new NonIdempotent() {
public Message<Response>
apply(final String message) throws Exception {
/*
* SECURITY CLAIM: do request processing inside once block
* to ensure application layer cannot detect request replay
*/
final Dispatch lambda = Dispatch.post(target, p);
if (null == lambda) { // no such method
exports._.log.got(message, null, null);
exports._.log.returned(message + "-return");
final boolean get = null != Dispatch.get(target, p);
return new Message<Response>(Response.notAllowed(
get ? new String[]{"TRACE","OPTIONS","GET"} :
new String[]{"TRACE","OPTIONS" }), null);
} // method invocation
if (null != message) {
exports._.log.got(message, null, lambda.implementation);
}
Object value;
try {
String contentType = m.head.getContentType();
if (null == contentType) {
contentType = FileType.json.name;
} else {
final int end = contentType.indexOf(';');
if (-1 != end) {
contentType = contentType.substring(0, end);
}
}
final Deserializer syntax =
Header.equivalent(FileType.json.name, contentType)||
Header.equivalent("text/plain", contentType) ?
new JSONDeserializer() : null;
final ConstArray<?> argv;
try {
argv = null == syntax ? ConstArray.array(m.body) :
syntax.deserializeTuple(m.body.asInputStream(),
exports.connect(), exports.getHere(),
exports.code, lambda.implementation.
getGenericParameterTypes());
} catch (final BadSyntax e) {
/*
* strip out the parsing information to avoid
* leaking information to the application layer
*/
throw (Exception)e.getCause();
}
// AUDIT: call to untrusted application code
value = Reflection.invoke(lambda.declaration, target,
argv.toArray(new Object[argv.length()]));
if (Fulfilled.isInstance(value)) {
value = ((Promise<?>)value).call();
}
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Type R = lambda.declaration.getGenericReturnType();
if (null != message) {
if (null!=value || (void.class!=R && Void.class!=R)) {
exports._.log.returned(message + "-return");
}
}
return serialize(m.head.method, "200", "OK",
Server.ephemeral, R, value);
}
});
}
final boolean get = null != Dispatch.get(target, p);
final boolean post = null != Dispatch.post(target, p);
final String[] allow =
get && post ? new String[] { "TRACE", "OPTIONS", "GET", "POST" } :
get ? new String[] { "TRACE", "OPTIONS", "GET" } :
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" };
return "OPTIONS".equals(m.head.method) ?
new Message<Response>(Response.options(allow), null) :
new Message<Response>(Response.notAllowed(allow), null);
}
private Message<Response>
serialize(final String method, final String status,
final String phrase, final int maxAge,
final Type type, final Object value) throws Exception {
final String contentType;
final ByteArray content;
if (value instanceof ByteArray) {
contentType = FileType.unknown.name;
content = (ByteArray)value;
} else {
contentType = FileType.json.name;
content=new JSONSerializer().serialize(exports.export(),type,value);
}
if ("GET".equals(method) || "HEAD".equals(method)) {
return new Message<Response>(new Response(
"HTTP/1.1", status, phrase,
PowerlessArray.array(
new Header("Cache-Control",
"must-revalidate, max-age=" + maxAge),
new Header("Content-Type", contentType),
new Header("Content-Length", "" + content.length())
)),
"HEAD".equals(method) ? null : content);
}
return new Message<Response>(new Response(
"HTTP/1.1", status, phrase,
PowerlessArray.array(
new Header("Content-Type", contentType),
new Header("Content-Length", "" + content.length())
)), content);
}
}
| true | true | protected Message<Response>
apply(final String query, final Message<Request> m) throws Exception {
// further dispatch the request based on the accessed member
final String p = HTTP.predicate(m.head.method, query);
if (null == p) { // when block
if ("OPTIONS".equals(m.head.method)) {
return new Message<Response>(
Response.options("TRACE", "OPTIONS", "GET", "HEAD"), null);
}
if (!("GET".equals(m.head.method) || "HEAD".equals(m.head.method))){
return new Message<Response>(
Response.notAllowed("TRACE","OPTIONS","GET","HEAD"), null);
}
Object value;
try {
// AUDIT: call to untrusted application code
value = Eventual.ref(exports.reference(query)).call();
} catch (final Unresolved e) {
return serialize(m.head.method, "404", "not yet",
Server.ephemeral, Exception.class, e);
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Response failed = m.head.allow("\"\"");
if (null != failed) { return new Message<Response>(failed, null); }
return serialize(m.head.method, "200", "OK", Server.forever,
Object.class, value);
} // member access
// determine the target object
final Object target;
try {
final Promise<?> subject = Eventual.ref(exports.reference(query));
// to preserve message order, only access members on a fulfilled ref
if (!Fulfilled.isInstance(subject)) { throw new Unresolved(); }
target = subject.call();
} catch (final Exception e) {
return serialize(m.head.method, "404", "never", Server.forever,
Exception.class, e);
}
if ("GET".equals(m.head.method) || "HEAD".equals(m.head.method)) {
final Dispatch property = Dispatch.get(target, p);
if (null == property) { // no such property
final boolean post = null != Dispatch.post(target, p);
return new Message<Response>(Response.notAllowed(
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" }), null);
}
Object value; // property access
try {
// AUDIT: call to untrusted application code
final Object r = Reflection.invoke(property.declaration,target);
value = Fulfilled.isInstance(r) ? ((Promise<?>)r).call() : r;
} catch (final Exception e) {
value = Eventual.reject(e);
}
final String etag = exports.getTransactionTag();
final Response failed = m.head.allow(etag);
if (null != failed) { return new Message<Response>(failed, null); }
Message<Response> r = serialize(
m.head.method, "200", "OK", Server.ephemeral,
property.implementation.getGenericReturnType(), value);
if (null != etag) {
r = new Message<Response>(r.head.with("ETag", etag), r.body);
}
return r;
}
if ("POST".equals(m.head.method)) {
final Response failed = m.head.allow(null);
if (null != failed) { return new Message<Response>(failed, null); }
return exports.execute(query, new NonIdempotent() {
public Message<Response>
apply(final String message) throws Exception {
/*
* SECURITY CLAIM: do request processing inside once block
* to ensure application layer cannot detect request replay
*/
final Dispatch lambda = Dispatch.post(target, p);
if (null == lambda) { // no such method
exports._.log.got(message, null, null);
exports._.log.returned(message + "-return");
final boolean get = null != Dispatch.get(target, p);
return new Message<Response>(Response.notAllowed(
get ? new String[]{"TRACE","OPTIONS","GET"} :
new String[]{"TRACE","OPTIONS" }), null);
} // method invocation
if (null != message) {
exports._.log.got(message, null, lambda.implementation);
}
Object value;
try {
String contentType = m.head.getContentType();
if (null == contentType) {
contentType = FileType.json.name;
} else {
final int end = contentType.indexOf(';');
if (-1 != end) {
contentType = contentType.substring(0, end);
}
}
final Deserializer syntax =
Header.equivalent(FileType.json.name, contentType)||
Header.equivalent("text/plain", contentType) ?
new JSONDeserializer() : null;
final ConstArray<?> argv;
try {
argv = null == syntax ? ConstArray.array(m.body) :
syntax.deserializeTuple(m.body.asInputStream(),
exports.connect(), exports.getHere(),
exports.code, lambda.implementation.
getGenericParameterTypes());
} catch (final BadSyntax e) {
/*
* strip out the parsing information to avoid
* leaking information to the application layer
*/
throw (Exception)e.getCause();
}
// AUDIT: call to untrusted application code
value = Reflection.invoke(lambda.declaration, target,
argv.toArray(new Object[argv.length()]));
if (Fulfilled.isInstance(value)) {
value = ((Promise<?>)value).call();
}
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Type R = lambda.declaration.getGenericReturnType();
if (null != message) {
if (null!=value || (void.class!=R && Void.class!=R)) {
exports._.log.returned(message + "-return");
}
}
return serialize(m.head.method, "200", "OK",
Server.ephemeral, R, value);
}
});
}
final boolean get = null != Dispatch.get(target, p);
final boolean post = null != Dispatch.post(target, p);
final String[] allow =
get && post ? new String[] { "TRACE", "OPTIONS", "GET", "POST" } :
get ? new String[] { "TRACE", "OPTIONS", "GET" } :
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" };
return "OPTIONS".equals(m.head.method) ?
new Message<Response>(Response.options(allow), null) :
new Message<Response>(Response.notAllowed(allow), null);
}
| protected Message<Response>
apply(final String query, final Message<Request> m) throws Exception {
// further dispatch the request based on the accessed member
final String p = HTTP.predicate(m.head.method, query);
if (null == p) { // when block
if ("OPTIONS".equals(m.head.method)) {
return new Message<Response>(
Response.options("TRACE", "OPTIONS", "GET", "HEAD"), null);
}
if (!("GET".equals(m.head.method) || "HEAD".equals(m.head.method))){
return new Message<Response>(
Response.notAllowed("TRACE","OPTIONS","GET","HEAD"), null);
}
Object value;
try {
// AUDIT: call to untrusted application code
value = Eventual.ref(exports.reference(query)).call();
} catch (final Unresolved e) {
return serialize(m.head.method, "404", "not yet",
Server.ephemeral, Exception.class, e);
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Response failed = m.head.allow("\"\"");
if (null != failed) { return new Message<Response>(failed, null); }
return serialize(m.head.method, "200", "OK", Server.forever,
Object.class, value);
} // member access
// determine the target object
final Object target;
try {
final Promise<?> subject = Eventual.ref(exports.reference(query));
// to preserve message order, only access members on a fulfilled ref
if (!Fulfilled.isInstance(subject)) { throw new Unresolved(); }
target = subject.call();
} catch (final Exception e) {
return serialize(m.head.method, "404", "never", Server.forever,
Exception.class, e);
}
if ("GET".equals(m.head.method) || "HEAD".equals(m.head.method)) {
final Dispatch property = Dispatch.get(target, p);
if (null == property) { // no such property
final boolean post = null != Dispatch.post(target, p);
return new Message<Response>(Response.notAllowed(
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" }), null);
}
Object value; // property access
try {
// AUDIT: call to untrusted application code
final Object r = Reflection.invoke(property.declaration,target);
value = Fulfilled.isInstance(r) ? ((Promise<?>)r).call() : r;
} catch (final Exception e) {
value = Eventual.reject(e);
}
final String etag = exports.getTransactionTag();
final Response failed = m.head.allow(etag);
if (null != failed) { return new Message<Response>(failed, null); }
Message<Response> r = serialize(
m.head.method, "200", "OK", Server.ephemeral,
property.declaration.getGenericReturnType(), value);
if (null != etag) {
r = new Message<Response>(r.head.with("ETag", etag), r.body);
}
return r;
}
if ("POST".equals(m.head.method)) {
final Response failed = m.head.allow(null);
if (null != failed) { return new Message<Response>(failed, null); }
return exports.execute(query, new NonIdempotent() {
public Message<Response>
apply(final String message) throws Exception {
/*
* SECURITY CLAIM: do request processing inside once block
* to ensure application layer cannot detect request replay
*/
final Dispatch lambda = Dispatch.post(target, p);
if (null == lambda) { // no such method
exports._.log.got(message, null, null);
exports._.log.returned(message + "-return");
final boolean get = null != Dispatch.get(target, p);
return new Message<Response>(Response.notAllowed(
get ? new String[]{"TRACE","OPTIONS","GET"} :
new String[]{"TRACE","OPTIONS" }), null);
} // method invocation
if (null != message) {
exports._.log.got(message, null, lambda.implementation);
}
Object value;
try {
String contentType = m.head.getContentType();
if (null == contentType) {
contentType = FileType.json.name;
} else {
final int end = contentType.indexOf(';');
if (-1 != end) {
contentType = contentType.substring(0, end);
}
}
final Deserializer syntax =
Header.equivalent(FileType.json.name, contentType)||
Header.equivalent("text/plain", contentType) ?
new JSONDeserializer() : null;
final ConstArray<?> argv;
try {
argv = null == syntax ? ConstArray.array(m.body) :
syntax.deserializeTuple(m.body.asInputStream(),
exports.connect(), exports.getHere(),
exports.code, lambda.implementation.
getGenericParameterTypes());
} catch (final BadSyntax e) {
/*
* strip out the parsing information to avoid
* leaking information to the application layer
*/
throw (Exception)e.getCause();
}
// AUDIT: call to untrusted application code
value = Reflection.invoke(lambda.declaration, target,
argv.toArray(new Object[argv.length()]));
if (Fulfilled.isInstance(value)) {
value = ((Promise<?>)value).call();
}
} catch (final Exception e) {
value = Eventual.reject(e);
}
final Type R = lambda.declaration.getGenericReturnType();
if (null != message) {
if (null!=value || (void.class!=R && Void.class!=R)) {
exports._.log.returned(message + "-return");
}
}
return serialize(m.head.method, "200", "OK",
Server.ephemeral, R, value);
}
});
}
final boolean get = null != Dispatch.get(target, p);
final boolean post = null != Dispatch.post(target, p);
final String[] allow =
get && post ? new String[] { "TRACE", "OPTIONS", "GET", "POST" } :
get ? new String[] { "TRACE", "OPTIONS", "GET" } :
post ? new String[] { "TRACE", "OPTIONS", "POST" } :
new String[] { "TRACE", "OPTIONS" };
return "OPTIONS".equals(m.head.method) ?
new Message<Response>(Response.options(allow), null) :
new Message<Response>(Response.notAllowed(allow), null);
}
|
diff --git a/src/com/jmex/model/XMLparser/Converters/ObjToJme.java b/src/com/jmex/model/XMLparser/Converters/ObjToJme.java
index 56fef137b..eeb15fe2b 100755
--- a/src/com/jmex/model/XMLparser/Converters/ObjToJme.java
+++ b/src/com/jmex/model/XMLparser/Converters/ObjToJme.java
@@ -1,400 +1,400 @@
/*
* Copyright (c) 2003-2005 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jmex.model.XMLparser.Converters;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.geom.BufferUtils;
import com.jmex.model.XMLparser.JmeBinaryWriter;
/**
* Started Date: Jul 17, 2004<br><br>
*
* Converts .obj files into .jme binary format. In order for ObjToJme to find the .mtl library, you must specify the
* "mtllib" tag to the baseURL where the mtl libraries are to be found. Somewhat similar to this.setProperty("mtllib",objFile);
*
* @author Jack Lindamood
*/
public class ObjToJme extends FormatConverter{
private BufferedReader inFile;
/** Every vertex in the file*/
private ArrayList vertexList=new ArrayList();
/** Every texture coordinate in the file*/
private ArrayList textureList=new ArrayList();
/** Every normal in the file*/
private ArrayList normalList=new ArrayList();
/** Last 'material' flag in the file*/
private MaterialGrouping curGroup;
/** Default material group for groups without a material*/
private final MaterialGrouping DEFAULT_GROUP=new MaterialGrouping();
/** Maps material names to the actual material object **/
private HashMap materialNames=new HashMap();
/** Maps Materials to their vertex usage **/
private HashMap materialSets=new HashMap();
/**
* Converts an Obj file to jME format. The syntax is: "ObjToJme file.obj outfile.jme".
* @param args The array of parameters
*/
public static void main(String[] args){
new DummyDisplaySystem();
new ObjToJme().attemptFileConvert(args);
}
/**
* Converts an .obj file to .jme format. If you wish to use a .mtl to load the obj's material information please specify
* the base url where the .mtl is located with setProperty("mtllib",new URL(baseURL))
* @param format The .obj file's stream.
* @param jMEFormat The .jme file's stream.
* @throws IOException If anything bad happens.
*/
public void convert(InputStream format, OutputStream jMEFormat) throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
materialSets.clear();
materialNames.clear();
inFile=new BufferedReader(new InputStreamReader(format));
String in;
curGroup=DEFAULT_GROUP;
materialSets.put(DEFAULT_GROUP,new ArraySet());
while ((in=inFile.readLine())!=null){
processLine(in);
}
new JmeBinaryWriter().writeScene(buildStructure(),jMEFormat);
nullAll();
}
/**
* Nulls all to let the gc do its job.
* @throws IOException
*/
private void nullAll() throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
curGroup=null;
materialSets.clear();
materialNames.clear();
inFile.close();
inFile=null;
}
/**
* Converts the structures of the .obj file to a scene to write
* @return The TriMesh or Node that represents the .obj file.
*/
private Spatial buildStructure() {
Node toReturn=new Node("obj file");
Object[] o=materialSets.keySet().toArray();
for (int i=0;i<o.length;i++){
MaterialGrouping thisGroup=(MaterialGrouping) o[i];
ArraySet thisSet=(ArraySet) materialSets.get(thisGroup);
if (thisSet.indexes.size()<3) continue;
TriMesh thisMesh=new TriMesh("temp"+i);
Vector3f[] vert=new Vector3f[thisSet.vertexes.size()];
Vector3f[] norm=new Vector3f[thisSet.vertexes.size()];
Vector2f[] text=new Vector2f[thisSet.vertexes.size()];
for (int j=0;j<thisSet.vertexes.size();j++){
vert[j]=(Vector3f) thisSet.vertexes.get(j);
norm[j]=(Vector3f) thisSet.normals.get(j);
text[j]=(Vector2f) thisSet.textures.get(j);
}
int[] indexes=new int[thisSet.indexes.size()];
for (int j=0;j<thisSet.indexes.size();j++)
indexes[j]=((Integer)thisSet.indexes.get(j)).intValue();
thisMesh.reconstruct(BufferUtils.createFloatBuffer(vert),
BufferUtils.createFloatBuffer(norm), null,
BufferUtils.createFloatBuffer(text),
BufferUtils.createIntBuffer(indexes));
if (properties.get("sillycolors")!=null)
thisMesh.setRandomColors();
if (thisGroup.ts.isEnabled()) thisMesh.setRenderState(thisGroup.ts);
thisMesh.setRenderState(thisGroup.m);
toReturn.attachChild(thisMesh);
}
if (toReturn.getQuantity()==1)
return toReturn.getChild(0);
else
return toReturn;
}
/**
* Processes a line of text in the .obj file.
* @param s The line of text in the file.
* @throws IOException
*/
private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
//see what the material name is if there isn't a name, assume its the default group
if (parts.length >= 2 && materialNames.get(parts[1]) != null
&& materialNames.get(parts[1]) != null)
curGroup = (MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
- } else if ("Ks".equals(parts[0])){
+ } else if ("Ns".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
private String[] removeEmpty(String[] parts) {
int cnt=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals(""))
cnt++;
}
String[] toReturn=new String[cnt];
int index=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals("")){
toReturn[index++]=parts[i];
}
}
return toReturn;
}
private void addMaterial(String[] parts) {
MaterialGrouping newMat=new MaterialGrouping();
materialNames.put(parts[1],newMat);
materialSets.put(newMat,new ArraySet());
curGroup=newMat;
}
private void loadMaterials(String[] fileNames) throws IOException {
URL matURL=(URL) properties.get("mtllib");
if (matURL==null) return;
for (int i=1;i<fileNames.length;i++){
processMaterialFile(new URL(matURL,fileNames[i]).openStream());
}
}
private void processMaterialFile(InputStream inputStream) throws IOException {
BufferedReader matFile=new BufferedReader(new InputStreamReader(inputStream));
String in;
while ((in=matFile.readLine())!=null){
processLine(in);
}
}
private void addFaces(String[] parts) {
ArraySet thisMat=(ArraySet) materialSets.get(curGroup);
IndexSet first=new IndexSet(parts[1]);
int firstIndex=thisMat.findSet(first);
IndexSet second=new IndexSet(parts[2]);
int secondIndex=thisMat.findSet(second);
IndexSet third=new IndexSet();
for (int i=3;i<parts.length;i++){
third.parseStringArray(parts[i]);
thisMat.indexes.add(new Integer(firstIndex));
thisMat.indexes.add(new Integer(secondIndex));
int thirdIndex=thisMat.findSet(third);
thisMat.indexes.add(new Integer(thirdIndex));
}
}
private void setDefaultGroup() {
curGroup=DEFAULT_GROUP;
}
private void addNormalToList(String[] parts) {
normalList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private void addTextoList(String[] parts) {
if (parts.length==2)
textureList.add(new Vector2f(Float.parseFloat(parts[1]),0));
else
textureList.add(new Vector2f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2])));
}
private void addVertextoList(String[] parts) {
vertexList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private class MaterialGrouping{
public MaterialGrouping(){
m=DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
m.setAmbient(new ColorRGBA(.2f,.2f,.2f,1));
m.setDiffuse(new ColorRGBA(.8f,.8f,.8f,1));
m.setSpecular(ColorRGBA.white);
m.setEnabled(true);
ts=DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
}
MaterialState m;
TextureState ts;
}
/**
* Stores a complete set of vertex/texture/normal triplet set that is to be indexed by the TriMesh.
*/
private class IndexSet{
public IndexSet(){}
public IndexSet(String parts){
parseStringArray(parts);
}
public void parseStringArray(String parts){
int vIndex,nIndex,tIndex;
String[] triplet=parts.split("/");
vIndex=Integer.parseInt(triplet[0]);
if (vIndex<0){
vertex=(Vector3f) vertexList.get(vertexList.size()+vIndex);
} else{
vertex=(Vector3f) vertexList.get(vIndex-1); // obj is 1 indexed
}
if (triplet[1]==null || triplet[1].equals("")){
texture=null;
} else{
tIndex=Integer.parseInt(triplet[1]);
if (tIndex<0){
texture=(Vector2f) textureList.get(textureList.size()+tIndex);
} else{
texture=(Vector2f) textureList.get(tIndex-1); // obj is 1 indexed
}
}
if (triplet.length!=3 || triplet[2]==null || triplet[2].equals("")){
normal=null;
} else{
nIndex=Integer.parseInt(triplet[2]);
if (nIndex<0){
normal=(Vector3f) normalList.get(normalList.size()+nIndex);
} else{
normal=(Vector3f) normalList.get(nIndex-1); // obj is 1 indexed
}
}
}
Vector3f vertex;
Vector2f texture;
Vector3f normal;
}
/**
* An array of information that will become a renderable trimesh. Each material has it's own trimesh.
*/
private class ArraySet{
private ArrayList vertexes=new ArrayList();
private ArrayList normals=new ArrayList();
private ArrayList textures=new ArrayList();
private ArrayList indexes=new ArrayList();
public int findSet(IndexSet v) {
int i=0;
for (i=0;i<normals.size();i++){
if (compareObjects(v.normal,normals.get(i)) &&
compareObjects(v.texture,textures.get(i)) &&
compareObjects(v.vertex,vertexes.get(i)))
return i;
}
normals.add(v.normal);
textures.add(v.texture);
vertexes.add(v.vertex);
return i;
}
private boolean compareObjects(Object o1, Object o2) {
if (o1==null) return (o2==null);
if (o2==null) return false;
return o1.equals(o2);
}
}
}
| true | true | private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
//see what the material name is if there isn't a name, assume its the default group
if (parts.length >= 2 && materialNames.get(parts[1]) != null
&& materialNames.get(parts[1]) != null)
curGroup = (MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
| private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
//see what the material name is if there isn't a name, assume its the default group
if (parts.length >= 2 && materialNames.get(parts[1]) != null
&& materialNames.get(parts[1]) != null)
curGroup = (MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ns".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
|
diff --git a/main/src/cgeo/geocaching/CacheDetailActivity.java b/main/src/cgeo/geocaching/CacheDetailActivity.java
index 273aa8c21..fe6693b49 100644
--- a/main/src/cgeo/geocaching/CacheDetailActivity.java
+++ b/main/src/cgeo/geocaching/CacheDetailActivity.java
@@ -1,2662 +1,2662 @@
package cgeo.geocaching;
import butterknife.InjectView;
import butterknife.Views;
import cgeo.calendar.ICalendar;
import cgeo.geocaching.activity.AbstractViewPagerActivity;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.GCConnector;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.GeopointFormatter;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.ui.AbstractCachingPageViewCreator;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.CoordinatesFormatSwitcher;
import cgeo.geocaching.ui.DecryptTextClickListener;
import cgeo.geocaching.ui.EditNoteDialog;
import cgeo.geocaching.ui.EditNoteDialog.EditNoteDialogListener;
import cgeo.geocaching.ui.Formatter;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.LoggingUI;
import cgeo.geocaching.ui.WeakReferenceHandler;
import cgeo.geocaching.utils.BaseUtils;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.ClipboardUtils;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.GeoDirHandler;
import cgeo.geocaching.utils.HtmlUtils;
import cgeo.geocaching.utils.ImageHelper;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MatcherWrapper;
import cgeo.geocaching.utils.RunnableWithArgument;
import cgeo.geocaching.utils.TranslationUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import android.R.color;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* Activity to handle all single-cache-stuff.
*
* e.g. details, description, logs, waypoints, inventory...
*/
public class CacheDetailActivity extends AbstractViewPagerActivity<CacheDetailActivity.Page>
implements EditNoteDialogListener {
private static final int MENU_FIELD_COPY = 1;
private static final int MENU_FIELD_TRANSLATE = 2;
private static final int MENU_FIELD_TRANSLATE_EN = 3;
private static final int MENU_FIELD_SHARE = 4;
private static final int MENU_SHARE = 12;
private static final int MENU_CALENDAR = 11;
private static final int MENU_CACHES_AROUND = 10;
private static final int MENU_BROWSER = 7;
private static final int MENU_DEFAULT_NAVIGATION = 13;
private static final int CONTEXT_MENU_WAYPOINT_EDIT = 1234;
private static final int CONTEXT_MENU_WAYPOINT_DUPLICATE = 1235;
private static final int CONTEXT_MENU_WAYPOINT_DELETE = 1236;
private static final int CONTEXT_MENU_WAYPOINT_NAVIGATE = 1238;
private static final int CONTEXT_MENU_WAYPOINT_CACHES_AROUND = 1239;
private static final int CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION = 1240;
private static final int CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES = 1241;
private static final Pattern DARK_COLOR_PATTERN = Pattern.compile(Pattern.quote("color=\"#") + "(0[0-9]){3}" + "\"");
public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex";
private Geocache cache;
private final Progress progress = new Progress();
private SearchResult search;
private EditNoteDialogListener editNoteDialogListener;
private final GeoDirHandler locationUpdater = new GeoDirHandler() {
@Override
public void updateGeoData(final IGeoData geo) {
if (cacheDistanceView == null) {
return;
}
try {
final StringBuilder dist = new StringBuilder();
if (geo.getCoords() != null && cache != null && cache.getCoords() != null) {
dist.append(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(cache.getCoords())));
}
if (cache != null && cache.getElevation() != null) {
if (geo.getAltitude() != 0.0) {
final float diff = (float) (cache.getElevation() - geo.getAltitude());
dist.append(' ').append(Units.getElevation(diff));
}
}
cacheDistanceView.setText(dist.toString());
cacheDistanceView.bringToFront();
} catch (Exception e) {
Log.w("Failed to update location.");
}
}
};
private CharSequence clickedItemText = null;
private int contextMenuWPIndex = -1;
/**
* If another activity is called and can modify the data of this activity, we refresh it on resume.
*/
private boolean refreshOnResume = false;
// some views that must be available from everywhere // TODO: Reference can block GC?
private TextView cacheDistanceView;
private Handler cacheChangeNotificationHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
notifyDataSetChanged();
}
};
protected ImagesList imagesList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.cacheview);
// set title in code, as the activity needs a hard coded title due to the intent filters
setTitle(res.getString(R.string.cache));
String geocode = null;
// TODO Why can it happen that search is not null? onCreate should be called only once and it is not set before.
if (search != null) {
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache != null && cache.getGeocode() != null) {
geocode = cache.getGeocode();
}
}
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = getIntent().getData();
// try to get data from extras
String name = null;
String guid = null;
if (geocode == null && extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
String uriHost = uri.getHost().toLowerCase(Locale.US);
String uriPath = uri.getPath().toLowerCase(Locale.US);
String uriQuery = uri.getQuery();
if (uriQuery != null) {
Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
} else {
Log.i("Opening URI: " + uriHost + uriPath);
}
if (uriHost.contains("geocaching.com")) {
geocode = uri.getQueryParameter("wp");
guid = uri.getQueryParameter("guid");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
} else if (uriHost.contains("coord.info")) {
if (uriPath != null && uriPath.startsWith("/gc")) {
geocode = uriPath.substring(1).toUpperCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
}
// no given data
if (geocode == null && guid == null) {
showToast(res.getString(R.string.err_detail_cache));
finish();
return;
}
final LoadCacheHandler loadCacheHandler = new LoadCacheHandler();
try {
String title = res.getString(R.string.cache);
if (StringUtils.isNotBlank(name)) {
title = name;
} else if (null != geocode && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
title = geocode;
}
progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage());
} catch (Exception e) {
// nothing, we lost the window
}
ImageView defaultNavigationImageView = (ImageView) findViewById(R.id.defaultNavigation);
defaultNavigationImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startDefaultNavigation2();
return true;
}
});
final int pageToOpen = savedInstanceState != null ?
savedInstanceState.getInt(STATE_PAGE_INDEX, 0) :
Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
createViewPager(pageToOpen, new OnPageSelectedListener() {
@Override
public void onPageSelected(int position) {
if (Settings.isOpenLastDetailsPage()) {
Settings.setLastDetailsPage(position);
}
// lazy loading of cache images
if (getPage(position) == Page.IMAGES) {
loadCacheImages();
}
}
});
// Initialization done. Let's load the data with the given information.
new LoadCacheThread(geocode, guid, loadCacheHandler).start();
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_PAGE_INDEX, getCurrentItem());
}
@Override
public void onResume() {
super.onResume();
if (refreshOnResume) {
notifyDataSetChanged();
refreshOnResume = false;
}
locationUpdater.startGeo();
}
@Override
public void onStop() {
if (cache != null) {
cache.setChangeNotificationHandler(null);
}
super.onStop();
}
@Override
public void onPause() {
locationUpdater.stopGeo();
super.onPause();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
contextMenuWPIndex = -1;
switch (viewId) {
case R.id.value: // coordinates, gc-code, name
clickedItemText = ((TextView) view).getText();
String itemTitle = (String) ((TextView) ((View) view.getParent()).findViewById(R.id.name)).getText();
buildOptionsContextmenu(menu, viewId, itemTitle, true);
break;
case R.id.shortdesc:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_description), false);
break;
case R.id.longdesc:
// combine short and long description
String shortDesc = cache.getShortDescription();
if (StringUtils.isBlank(shortDesc)) {
clickedItemText = ((TextView) view).getText();
} else {
clickedItemText = shortDesc + "\n\n" + ((TextView) view).getText();
}
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_description), false);
break;
case R.id.personalnote:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_personal_note), true);
break;
case R.id.hint:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_hint), false);
break;
case R.id.log:
clickedItemText = ((TextView) view).getText();
buildOptionsContextmenu(menu, viewId, res.getString(R.string.cache_logs), false);
break;
case -1:
if (null != cache.getWaypoints()) {
try {
final ViewGroup parent = ((ViewGroup) view.getParent());
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i) == view) {
final List<Waypoint> sortedWaypoints = new ArrayList<Waypoint>(cache.getWaypoints());
Collections.sort(sortedWaypoints);
final Waypoint waypoint = sortedWaypoints.get(i);
final int index = cache.getWaypoints().indexOf(waypoint);
menu.setHeaderTitle(res.getString(R.string.waypoint));
if (waypoint.getWaypointType().equals(WaypointType.ORIGINAL)) {
menu.add(CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES, index, 0, R.string.waypoint_reset_cache_coords);
} else {
menu.add(CONTEXT_MENU_WAYPOINT_EDIT, index, 0, R.string.waypoint_edit);
menu.add(CONTEXT_MENU_WAYPOINT_DUPLICATE, index, 0, R.string.waypoint_duplicate);
}
contextMenuWPIndex = index;
if (waypoint.isUserDefined() && !waypoint.getWaypointType().equals(WaypointType.ORIGINAL)) {
menu.add(CONTEXT_MENU_WAYPOINT_DELETE, index, 0, R.string.waypoint_delete);
}
if (waypoint.getCoords() != null) {
menu.add(CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION, index, 0, NavigationAppFactory.getDefaultNavigationApplication().getName());
menu.add(CONTEXT_MENU_WAYPOINT_NAVIGATE, index, 0, R.string.cache_menu_navigate).setIcon(R.drawable.ic_menu_mapmode);
menu.add(CONTEXT_MENU_WAYPOINT_CACHES_AROUND, index, 0, R.string.cache_menu_around);
}
break;
}
}
} catch (Exception e) {
}
}
break;
default:
if (imagesList != null) {
imagesList.onCreateContextMenu(menu, view);
}
break;
}
}
private void buildOptionsContextmenu(ContextMenu menu, int viewId, String fieldTitle, boolean copyOnly) {
menu.setHeaderTitle(fieldTitle);
menu.add(viewId, MENU_FIELD_COPY, 0, res.getString(android.R.string.copy));
if (!copyOnly) {
if (clickedItemText.length() > TranslationUtils.translationTextLengthToWarn) {
showToast(res.getString(R.string.translate_length_warning));
}
menu.add(viewId, MENU_FIELD_TRANSLATE, 0, res.getString(R.string.translate_to_sys_lang, Locale.getDefault().getDisplayLanguage()));
if (Settings.isUseEnglish() && !StringUtils.equals(Locale.getDefault().getLanguage(), Locale.ENGLISH.getLanguage())) {
menu.add(viewId, MENU_FIELD_TRANSLATE_EN, 0, res.getString(R.string.translate_to_english));
}
}
menu.add(viewId, MENU_FIELD_SHARE, 0, res.getString(R.string.cache_share_field));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final int groupId = item.getGroupId();
final int index = item.getItemId();
switch (groupId) {
case R.id.value:
case R.id.shortdesc:
case R.id.longdesc:
case R.id.personalnote:
case R.id.hint:
case R.id.log:
switch (index) {
case MENU_FIELD_COPY:
ClipboardUtils.copyToClipboard(clickedItemText);
showToast(res.getString(R.string.clipboard_copy_ok));
return true;
case MENU_FIELD_TRANSLATE:
TranslationUtils.startActivityTranslate(this, Locale.getDefault().getLanguage(), HtmlUtils.extractText(clickedItemText));
return true;
case MENU_FIELD_TRANSLATE_EN:
TranslationUtils.startActivityTranslate(this, Locale.ENGLISH.getLanguage(), HtmlUtils.extractText(clickedItemText));
return true;
case MENU_FIELD_SHARE:
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, clickedItemText.toString());
startActivity(Intent.createChooser(intent, res.getText(R.string.cache_share_field)));
return true;
default:
break;
}
break;
case CONTEXT_MENU_WAYPOINT_EDIT:
final Waypoint waypointEdit = cache.getWaypoint(index);
if (waypointEdit != null) {
EditWaypointActivity.startActivityEditWaypoint(this, waypointEdit.getId());
refreshOnResume = true;
}
break;
case CONTEXT_MENU_WAYPOINT_DUPLICATE:
final Waypoint waypointDuplicate = cache.getWaypoint(index);
if (cache.duplicateWaypoint(waypointDuplicate)) {
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
notifyDataSetChanged();
}
break;
case CONTEXT_MENU_WAYPOINT_DELETE:
final Waypoint waypointDelete = cache.getWaypoint(index);
if (cache.deleteWaypoint(waypointDelete)) {
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
notifyDataSetChanged();
}
break;
case CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION:
final Waypoint waypointNavigation = cache.getWaypoint(index);
if (waypointNavigation != null) {
NavigationAppFactory.startDefaultNavigationApplication(1, this, waypointNavigation);
}
break;
case CONTEXT_MENU_WAYPOINT_NAVIGATE:
final Waypoint waypointNav = cache.getWaypoint(contextMenuWPIndex);
if (waypointNav != null) {
NavigationAppFactory.showNavigationMenu(this, null, waypointNav, null);
}
break;
case CONTEXT_MENU_WAYPOINT_CACHES_AROUND:
final Waypoint waypointAround = cache.getWaypoint(index);
if (waypointAround != null) {
cgeocaches.startActivityCoordinates(this, waypointAround.getCoords());
}
break;
case CONTEXT_MENU_WAYPOINT_RESET_ORIGINAL_CACHE_COORDINATES:
final Waypoint waypointReset = cache.getWaypoint(index);
if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
createResetCacheCoordinatesDialog(cache, waypointReset).show();
}
else {
final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
new ResetCoordsThread(cache, handler, waypointReset, true, false, progressDialog).start();
}
break;
default:
if (imagesList != null && imagesList.onContextItemSelected(item)) {
return true;
}
return onOptionsItemSelected(item);
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (null != cache) {
menu.add(0, MENU_DEFAULT_NAVIGATION, 0, NavigationAppFactory.getDefaultNavigationApplication().getName()).setIcon(R.drawable.ic_menu_compass); // default navigation tool
final SubMenu subMenu = menu.addSubMenu(0, 0, 0, res.getString(R.string.cache_menu_navigate)).setIcon(R.drawable.ic_menu_mapmode);
NavigationAppFactory.addMenuItems(subMenu, cache);
menu.add(0, MENU_CALENDAR, 0, res.getString(R.string.cache_menu_event)).setIcon(R.drawable.ic_menu_agenda); // add event to calendar
LoggingUI.addMenuItems(this, menu, cache);
menu.add(0, MENU_CACHES_AROUND, 0, res.getString(R.string.cache_menu_around)).setIcon(R.drawable.ic_menu_rotate); // caches around
menu.add(0, MENU_BROWSER, 0, res.getString(R.string.cache_menu_browser)).setIcon(R.drawable.ic_menu_globe); // browser
menu.add(0, MENU_SHARE, 0, res.getString(R.string.cache_menu_share)).setIcon(R.drawable.ic_menu_share); // share cache
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (cache != null) {
menu.findItem(MENU_DEFAULT_NAVIGATION).setVisible(null != cache.getCoords());
menu.findItem(MENU_CALENDAR).setVisible(cache.canBeAddedToCalendar());
menu.findItem(MENU_CACHES_AROUND).setVisible(null != cache.getCoords() && cache.supportsCachesAround());
menu.findItem(MENU_BROWSER).setVisible(cache.canOpenInBrowser());
}
LoggingUI.onPrepareOptionsMenu(menu, cache);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int menuItem = item.getItemId();
switch (menuItem) {
case 0:
// no menu selected, but a new sub menu shown
return false;
case MENU_DEFAULT_NAVIGATION:
startDefaultNavigation();
return true;
case MENU_BROWSER:
cache.openInBrowser(this);
return true;
case MENU_CACHES_AROUND:
cgeocaches.startActivityCoordinates(this, cache.getCoords());
return true;
case MENU_CALENDAR:
addToCalendarWithIntent();
return true;
case MENU_SHARE:
if (cache != null) {
cache.shareCache(this, res);
return true;
}
return false;
default:
if (NavigationAppFactory.onMenuItemSelected(item, this, cache)) {
return true;
}
if (LoggingUI.onMenuItemSelected(item, this, cache)) {
refreshOnResume = true;
return true;
}
}
return true;
}
private class LoadCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(final Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
if (search == null) {
showToast(res.getString(R.string.err_dwld_details_failed));
progress.dismiss();
finish();
return;
}
if (search.getError() != null) {
showToast(res.getString(R.string.err_dwld_details_failed) + " " + search.getError().getErrorString(res) + ".");
progress.dismiss();
finish();
return;
}
updateStatusMsg(res.getString(R.string.cache_dialog_loading_details_status_render));
// Data loaded, we're ready to show it!
notifyDataSetChanged();
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_loading_details)
+ "\n\n"
+ msg);
}
@Override
public void handleCancel(final Object extra) {
finish();
}
}
private void notifyDataSetChanged() {
if (search == null) {
return;
}
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache == null) {
progress.dismiss();
showToast(res.getString(R.string.err_detail_cache_find_some));
finish();
return;
}
// allow cache to notify CacheDetailActivity when it changes so it can be reloaded
cache.setChangeNotificationHandler(cacheChangeNotificationHandler);
// action bar: title and icon
if (StringUtils.isNotBlank(cache.getName())) {
setTitle(cache.getName() + " (" + cache.getGeocode() + ')');
} else {
setTitle(cache.getGeocode());
}
((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cache.getType().markerId), null, null, null);
// reset imagesList so Images view page will be redrawn
imagesList = null;
reinitializeViewPager();
// rendering done! remove progress popup if any there
invalidateOptionsMenuCompatible();
progress.dismiss();
}
/**
* Loads the cache with the given geocode or guid.
*/
private class LoadCacheThread extends Thread {
private CancellableHandler handler = null;
private String geocode;
private String guid;
public LoadCacheThread(final String geocode, final String guid, final CancellableHandler handlerIn) {
handler = handlerIn;
if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
showToast(res.getString(R.string.err_detail_cache_forgot));
progress.dismiss();
finish();
return;
}
this.geocode = geocode;
this.guid = guid;
}
@Override
public void run() {
search = Geocache.searchByGeocode(geocode, StringUtils.isBlank(geocode) ? guid : null, 0, false, handler);
handler.sendMessage(Message.obtain());
}
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context
* The application's environment.
* @param action
* The Intent action to check for availability.
* @param uri
* The Intent URI to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
private static boolean isIntentAvailable(Context context, String action, Uri uri) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent;
if (uri == null) {
intent = new Intent(action);
} else {
intent = new Intent(action, uri);
}
final List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return !list.isEmpty();
}
private void addToCalendarWithIntent() {
final boolean calendarAddOnAvailable = isIntentAvailable(this, ICalendar.INTENT, Uri.parse(ICalendar.URI_SCHEME + "://" + ICalendar.URI_HOST));
if (calendarAddOnAvailable) {
final Parameters params = new Parameters(
ICalendar.PARAM_NAME, cache.getName(),
ICalendar.PARAM_NOTE, StringUtils.defaultString(cache.getPersonalNote()),
ICalendar.PARAM_HIDDEN_DATE, String.valueOf(cache.getHiddenDate().getTime()),
ICalendar.PARAM_URL, StringUtils.defaultString(cache.getUrl()),
ICalendar.PARAM_COORDS, cache.getCoords() == null ? "" : cache.getCoords().format(GeopointFormatter.Format.LAT_LON_DECMINUTE_RAW),
ICalendar.PARAM_LOCATION, StringUtils.defaultString(cache.getLocation()),
ICalendar.PARAM_SHORT_DESC, StringUtils.defaultString(cache.getShortDescription()),
ICalendar.PARAM_START_TIME_MINUTES, StringUtils.defaultString(cache.guessEventTimeMinutes())
);
startActivity(new Intent(ICalendar.INTENT,
Uri.parse(ICalendar.URI_SCHEME + "://" + ICalendar.URI_HOST + "?" + params.toString())));
} else {
// Inform user the calendar add-on is not installed and let them get it from Google Play
new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.addon_missing_title))
.setMessage(new StringBuilder(res.getString(R.string.helper_calendar_missing))
.append(' ')
.append(res.getString(R.string.addon_download_prompt))
.toString())
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(ICalendar.CALENDAR_ADDON_URI));
startActivity(intent);
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
private void startDefaultNavigation() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, cache);
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
private void startDefaultNavigation2() {
NavigationAppFactory.startDefaultNavigationApplication(2, this, cache);
}
/**
* Wrapper for the referenced method in the xml-layout.
*/
public void goDefaultNavigation(@SuppressWarnings("unused") View view) {
startDefaultNavigation();
}
/**
* referenced from XML view
*/
public void showNavigationMenu(@SuppressWarnings("unused") View view) {
NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true);
}
/**
* Listener for clicks on username
*/
private class UserActionsClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == null) {
return;
}
if (!cache.supportsUserActions()) {
return;
}
clickedItemText = ((TextView) view).getText().toString();
showUserActionsDialog(clickedItemText);
}
}
/**
* Listener for clicks on owner name
*/
private class OwnerActionsClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == null) {
return;
}
if (!cache.supportsUserActions()) {
return;
}
// Use real owner name vice the one owner chose to display
if (StringUtils.isNotBlank(cache.getOwnerUserId())) {
clickedItemText = cache.getOwnerUserId();
} else {
clickedItemText = ((TextView) view).getText().toString();
}
showUserActionsDialog(clickedItemText);
}
}
/**
* Opens a dialog to do actions on an username
*/
private void showUserActionsDialog(final CharSequence name) {
final CharSequence[] items = { res.getString(R.string.user_menu_view_hidden),
res.getString(R.string.user_menu_view_found),
res.getString(R.string.user_menu_open_browser),
res.getString(R.string.user_menu_send_message)
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(res.getString(R.string.user_menu_title) + " " + name);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
cgeocaches.startActivityOwner(CacheDetailActivity.this, name.toString());
return;
case 1:
cgeocaches.startActivityUserName(CacheDetailActivity.this, name.toString());
return;
case 2:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + Network.encode(name.toString()))));
return;
case 3:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/email/?u=" + Network.encode(name.toString()))));
return;
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void loadCacheImages() {
if (imagesList != null) {
return;
}
PageViewCreator creator = getViewCreator(Page.IMAGES);
if (creator == null) {
return;
}
View imageView = creator.getView();
if (imageView == null) {
return;
}
imagesList = new ImagesList(this, cache.getGeocode());
imagesList.loadImages(imageView, cache.getImages(), false);
}
public static void startActivity(final Context context, final String geocode) {
final Intent detailIntent = new Intent(context, CacheDetailActivity.class);
detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
context.startActivity(detailIntent);
}
/**
* Enum of all possible pages with methods to get the view and a title.
*/
public enum Page {
DETAILS(R.string.detail),
DESCRIPTION(R.string.cache_description),
LOGS(R.string.cache_logs),
LOGSFRIENDS(R.string.cache_logsfriends),
WAYPOINTS(R.string.cache_waypoints),
INVENTORY(R.string.cache_inventory),
IMAGES(R.string.cache_images);
final private int titleStringId;
Page(final int titleStringId) {
this.titleStringId = titleStringId;
}
}
private class AttributeViewBuilder {
private ViewGroup attributeIconsLayout; // layout for attribute icons
private ViewGroup attributeDescriptionsLayout; // layout for attribute descriptions
private boolean attributesShowAsIcons = true; // default: show icons
/**
* If the cache is from a non GC source, it might be without icons. Disable switching in those cases.
*/
private boolean noAttributeIconsFound = false;
private int attributeBoxMaxWidth;
public void fillView(final LinearLayout attributeBox) {
// first ensure that the view is empty
attributeBox.removeAllViews();
// maximum width for attribute icons is screen width - paddings of parents
attributeBoxMaxWidth = Compatibility.getDisplayWidth();
ViewParent child = attributeBox;
do {
if (child instanceof View) {
attributeBoxMaxWidth -= ((View) child).getPaddingLeft() + ((View) child).getPaddingRight();
}
child = child.getParent();
} while (child != null);
// delete views holding description / icons
attributeDescriptionsLayout = null;
attributeIconsLayout = null;
attributeBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// toggle between attribute icons and descriptions
toggleAttributeDisplay(attributeBox, attributeBoxMaxWidth);
}
});
// icons or text?
//
// also show icons when noAttributeImagesFound == true. Explanation:
// 1. no icons could be found in the first invocation of this method
// 2. user refreshes cache from web
// 3. now this method is called again
// 4. attributeShowAsIcons is false but noAttributeImagesFound is true
// => try to show them now
if (attributesShowAsIcons || noAttributeIconsFound) {
showAttributeIcons(attributeBox, attributeBoxMaxWidth);
} else {
showAttributeDescriptions(attributeBox);
}
}
/**
* lazy-creates the layout holding the icons of the caches attributes
* and makes it visible
*/
private void showAttributeIcons(LinearLayout attribBox, int parentWidth) {
if (attributeIconsLayout == null) {
attributeIconsLayout = createAttributeIconsLayout(parentWidth);
// no matching icons found? show text
if (noAttributeIconsFound) {
showAttributeDescriptions(attribBox);
return;
}
}
attribBox.removeAllViews();
attribBox.addView(attributeIconsLayout);
attributesShowAsIcons = true;
}
/**
* lazy-creates the layout holding the descriptions of the caches attributes
* and makes it visible
*/
private void showAttributeDescriptions(LinearLayout attribBox) {
if (attributeDescriptionsLayout == null) {
attributeDescriptionsLayout = createAttributeDescriptionsLayout();
}
attribBox.removeAllViews();
attribBox.addView(attributeDescriptionsLayout);
attributesShowAsIcons = false;
}
/**
* toggle attribute descriptions and icons
*/
private void toggleAttributeDisplay(LinearLayout attribBox, int parentWidth) {
// Don't toggle when there are no icons to show.
if (noAttributeIconsFound) {
return;
}
// toggle
if (attributesShowAsIcons) {
showAttributeDescriptions(attribBox);
} else {
showAttributeIcons(attribBox, parentWidth);
}
}
private ViewGroup createAttributeIconsLayout(int parentWidth) {
final LinearLayout rows = new LinearLayout(CacheDetailActivity.this);
rows.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
rows.setOrientation(LinearLayout.VERTICAL);
LinearLayout attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
noAttributeIconsFound = true;
for (String attributeName : cache.getAttributes()) {
// check if another attribute icon fits in this row
attributeRow.measure(0, 0);
int rowWidth = attributeRow.getMeasuredWidth();
FrameLayout fl = (FrameLayout) getLayoutInflater().inflate(R.layout.attribute_image, null);
ImageView iv = (ImageView) fl.getChildAt(0);
if ((parentWidth - rowWidth) < iv.getLayoutParams().width) {
// make a new row
attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
}
final boolean strikethru = !CacheAttribute.isEnabled(attributeName);
final CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib != null) {
noAttributeIconsFound = false;
Drawable d = res.getDrawable(attrib.drawableId);
iv.setImageDrawable(d);
// strike through?
if (strikethru) {
// generate strikethru image with same properties as attribute image
ImageView strikethruImage = new ImageView(CacheDetailActivity.this);
strikethruImage.setLayoutParams(iv.getLayoutParams());
d = res.getDrawable(R.drawable.attribute__strikethru);
strikethruImage.setImageDrawable(d);
fl.addView(strikethruImage);
}
} else {
Drawable d = res.getDrawable(R.drawable.attribute_unknown);
iv.setImageDrawable(d);
}
attributeRow.addView(fl);
}
return rows;
}
private LinearLayout newAttributeIconsRow() {
LinearLayout rowLayout = new LinearLayout(CacheDetailActivity.this);
rowLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
return rowLayout;
}
private ViewGroup createAttributeDescriptionsLayout() {
final LinearLayout descriptions = (LinearLayout) getLayoutInflater().inflate(
R.layout.attribute_descriptions, null);
final TextView attribView = (TextView) descriptions.getChildAt(0);
final StringBuilder buffer = new StringBuilder();
for (String attributeName : cache.getAttributes()) {
final boolean enabled = CacheAttribute.isEnabled(attributeName);
// search for a translation of the attribute
CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib == null) {
attrib = CacheAttribute.UNKNOWN;
}
attributeName = attrib.getL10n(enabled);
if (buffer.length() > 0) {
buffer.append('\n');
}
buffer.append(attributeName);
}
attribView.setText(buffer);
return descriptions;
}
}
/**
* Creator for details-view.
*/
private class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
/**
* Reference to the details list, so that the helper-method can access it without an additional argument
*/
private LinearLayout detailsList;
// TODO Do we need this thread-references?
private StoreCacheThread storeThread;
private RefreshCacheThread refreshThread;
private Thread watchlistThread;
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_details, null);
// Start loading preview map
if (Settings.isStoreOfflineMaps()) {
new PreviewMapTask().execute((Void) null);
}
detailsList = (LinearLayout) view.findViewById(R.id.details_list);
final CacheDetailsCreator details = new CacheDetailsCreator(CacheDetailActivity.this, detailsList);
// cache name (full name)
Spannable span = (new Spannable.Factory()).newSpannable(Html.fromHtml(cache.getName()).toString());
if (cache.isDisabled() || cache.isArchived()) { // strike
span.setSpan(new StrikethroughSpan(), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (cache.isArchived()) {
span.setSpan(new ForegroundColorSpan(res.getColor(R.color.archived_cache_color)), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
registerForContextMenu(details.add(R.string.cache_name, span));
details.add(R.string.cache_type, cache.getType().getL10n());
details.addSize(cache);
registerForContextMenu(details.add(R.string.cache_geocode, cache.getGeocode()));
details.addCacheState(cache);
details.addDistance(cache, cacheDistanceView);
cacheDistanceView = details.getValueView();
details.addDifficulty(cache);
details.addTerrain(cache);
details.addRating(cache);
// favorite count
if (cache.getFavoritePoints() > 0) {
details.add(R.string.cache_favorite, cache.getFavoritePoints() + "×");
}
// own rating
if (cache.getMyVote() > 0) {
details.addStars(R.string.cache_own_rating, cache.getMyVote());
}
// cache author
if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) {
TextView ownerView = details.add(R.string.cache_owner, "");
if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) {
ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE);
} else { // OwnerReal guaranteed to be not blank based on above
ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE);
}
ownerView.setOnClickListener(new OwnerActionsClickListener());
}
// cache hidden
if (cache.getHiddenDate() != null) {
long time = cache.getHiddenDate().getTime();
if (time > 0) {
String dateString = Formatter.formatFullDate(time);
if (cache.isEventCache()) {
dateString = DateUtils.formatDateTime(cgeoapplication.getInstance().getBaseContext(), time, DateUtils.FORMAT_SHOW_WEEKDAY) + ", " + dateString;
}
details.add(cache.isEventCache() ? R.string.cache_event : R.string.cache_hidden, dateString);
}
}
// cache location
if (StringUtils.isNotBlank(cache.getLocation())) {
details.add(R.string.cache_location, cache.getLocation());
}
// cache coordinates
if (cache.getCoords() != null) {
TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString());
valueView.setOnClickListener(new CoordinatesFormatSwitcher(cache.getCoords()));
registerForContextMenu(valueView);
}
// cache attributes
if (!cache.getAttributes().isEmpty()) {
new AttributeViewBuilder().fillView((LinearLayout) view.findViewById(R.id.attributes_innerbox));
view.findViewById(R.id.attributes_box).setVisibility(View.VISIBLE);
}
updateOfflineBox(view, cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener());
// watchlist
Button buttonWatchlistAdd = (Button) view.findViewById(R.id.add_to_watchlist);
Button buttonWatchlistRemove = (Button) view.findViewById(R.id.remove_from_watchlist);
buttonWatchlistAdd.setOnClickListener(new AddToWatchlistClickListener());
buttonWatchlistRemove.setOnClickListener(new RemoveFromWatchlistClickListener());
updateWatchlistBox();
// favorite points
Button buttonFavPointAdd = (Button) view.findViewById(R.id.add_to_favpoint);
Button buttonFavPointRemove = (Button) view.findViewById(R.id.remove_from_favpoint);
buttonFavPointAdd.setOnClickListener(new FavoriteAddClickListener());
buttonFavPointRemove.setOnClickListener(new FavoriteRemoveClickListener());
updateFavPointBox();
// list
Button buttonChangeList = (Button) view.findViewById(R.id.change_list);
buttonChangeList.setOnClickListener(new ChangeListClickListener());
updateListBox();
// data license
IConnector connector = ConnectorFactory.getConnector(cache);
if (connector != null) {
String license = connector.getLicenseText(cache);
if (StringUtils.isNotBlank(license)) {
view.findViewById(R.id.license_box).setVisibility(View.VISIBLE);
TextView licenseView = ((TextView) view.findViewById(R.id.license));
licenseView.setText(Html.fromHtml(license), BufferType.SPANNABLE);
licenseView.setClickable(true);
licenseView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
} else {
view.findViewById(R.id.license_box).setVisibility(View.GONE);
}
}
return view;
}
private class StoreCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
storeThread = null;
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_offline_save_message)
+ "\n\n"
+ msg);
}
}
private class RefreshCacheHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
refreshThread = null;
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
private void updateStatusMsg(final String msg) {
progress.setMessage(res.getString(R.string.cache_dialog_refresh_message)
+ "\n\n"
+ msg);
}
}
private class DropCacheHandler extends Handler {
@Override
public void handleMessage(Message msg) {
CacheDetailActivity.this.notifyDataSetChanged();
}
}
private class StoreCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title,
new RunnableWithArgument<Integer>() {
@Override
public void run(final Integer selectedListId) {
storeCache(selectedListId);
}
}, true, StoredList.TEMPORARY_LIST_ID);
} else {
storeCache(StoredList.TEMPORARY_LIST_ID);
}
}
protected void storeCache(int listId) {
final StoreCacheHandler storeCacheHandler = new StoreCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage());
if (storeThread != null) {
storeThread.interrupt();
}
storeThread = new StoreCacheThread(listId, storeCacheHandler);
storeThread.start();
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isNetworkConnected(getApplicationContext())) {
showToast(getString(R.string.err_server));
return;
}
final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage());
if (refreshThread != null) {
refreshThread.interrupt();
}
refreshThread = new RefreshCacheThread(refreshCacheHandler);
refreshThread.start();
}
}
private class StoreCacheThread extends Thread {
final private int listId;
final private CancellableHandler handler;
public StoreCacheThread(final int listId, final CancellableHandler handler) {
this.listId = listId;
this.handler = handler;
}
@Override
public void run() {
cache.store(listId, handler);
}
}
private class RefreshCacheThread extends Thread {
final private CancellableHandler handler;
public RefreshCacheThread(final CancellableHandler handler) {
this.handler = handler;
}
@Override
public void run() {
cache.refresh(cache.getListId(), handler);
handler.sendEmptyMessage(0);
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
final DropCacheHandler dropCacheHandler = new DropCacheHandler();
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
new DropCacheThread(dropCacheHandler).start();
}
}
private class DropCacheThread extends Thread {
private Handler handler = null;
public DropCacheThread(Handler handlerIn) {
handler = handlerIn;
}
@Override
public void run() {
cache.drop(handler);
}
}
/**
* Abstract Listener for add / remove buttons for watchlist
*/
private abstract class AbstractWatchlistClickListener implements View.OnClickListener {
public void doExecute(int titleId, int messageId, Thread thread) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_watchlist_still_managing));
return;
}
progress.show(CacheDetailActivity.this, res.getString(titleId), res.getString(messageId), true, null);
if (watchlistThread != null) {
watchlistThread.interrupt();
}
watchlistThread = thread;
watchlistThread.start();
}
}
/**
* Listener for "add to watchlist" button
*/
private class AddToWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_watchlist_add_title,
R.string.cache_dialog_watchlist_add_message,
new WatchlistAddThread(new WatchlistHandler()));
}
}
/**
* Listener for "remove from watchlist" button
*/
private class RemoveFromWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_watchlist_remove_title,
R.string.cache_dialog_watchlist_remove_message,
new WatchlistRemoveThread(new WatchlistHandler()));
}
}
/** Thread to add this cache to the watchlist of the user */
private class WatchlistAddThread extends Thread {
private final Handler handler;
public WatchlistAddThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.addToWatchlist(cache) ? 1 : -1);
}
}
/** Thread to remove this cache from the watchlist of the user */
private class WatchlistRemoveThread extends Thread {
private final Handler handler;
public WatchlistRemoveThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.removeFromWatchlist(cache) ? 1 : -1);
}
}
/** Thread to add this cache to the favorite list of the user */
private class FavoriteAddThread extends Thread {
private final Handler handler;
public FavoriteAddThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.addToFavorites(cache) ? 1 : -1);
}
}
/** Thread to remove this cache to the favorite list of the user */
private class FavoriteRemoveThread extends Thread {
private final Handler handler;
public FavoriteRemoveThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.sendEmptyMessage(GCConnector.removeFromFavorites(cache) ? 1 : -1);
}
}
private class FavoriteUpdateHandler extends Handler {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
if (msg.what == -1) {
showToast(res.getString(R.string.err_favorite_failed));
} else {
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
}
/**
* Listener for "add to favorites" button
*/
private class FavoriteAddClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_favorite_add_title,
R.string.cache_dialog_favorite_add_message,
new FavoriteAddThread(new FavoriteUpdateHandler()));
}
}
/**
* Listener for "remove from favorites" button
*/
private class FavoriteRemoveClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(View arg0) {
doExecute(R.string.cache_dialog_favorite_remove_title,
R.string.cache_dialog_favorite_remove_message,
new FavoriteRemoveThread(new FavoriteUpdateHandler()));
}
}
/**
* Listener for "change list" button
*/
private class ChangeListClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title,
new RunnableWithArgument<Integer>() {
@Override
public void run(final Integer selectedListId) {
switchListById(selectedListId);
}
}, true, cache.getListId());
}
}
/**
* move cache to another list
*
* @param listId
* the ID of the list
*/
public void switchListById(int listId) {
if (listId < 0) {
return;
}
Settings.saveLastList(listId);
cgData.moveToList(cache, listId);
updateListBox();
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateWatchlistBox() {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.watchlist_box);
boolean supportsWatchList = cache.supportsWatchList();
layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE);
if (!supportsWatchList) {
return;
}
Button buttonAdd = (Button) view.findViewById(R.id.add_to_watchlist);
Button buttonRemove = (Button) view.findViewById(R.id.remove_from_watchlist);
TextView text = (TextView) view.findViewById(R.id.watchlist_text);
if (cache.isOnWatchlist() || cache.isOwner()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_watchlist_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_watchlist_not_on);
}
// the owner of a cache has it always on his watchlist. Adding causes an error
if (cache.isOwner()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateFavPointBox() {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.favpoint_box);
boolean supportsFavoritePoints = cache.supportsFavoritePoints();
layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE);
if (!supportsFavoritePoints || cache.isOwner() || !Settings.isPremiumMember()) {
return;
}
Button buttonAdd = (Button) view.findViewById(R.id.add_to_favpoint);
Button buttonRemove = (Button) view.findViewById(R.id.remove_from_favpoint);
TextView text = (TextView) view.findViewById(R.id.favpoint_text);
if (cache.isFavorite()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_favpoint_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_favpoint_not_on);
}
// Add/remove to Favorites is only possible if the cache has been found
if (!cache.isFound()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides/updates list box
*/
private void updateListBox() {
View box = view.findViewById(R.id.list_box);
if (cache.isOffline()) {
// show box
box.setVisibility(View.VISIBLE);
// update text
TextView text = (TextView) view.findViewById(R.id.list_text);
StoredList list = cgData.getList(cache.getListId());
if (list != null) {
text.setText(res.getString(R.string.cache_list_text) + " " + list.title);
} else {
// this should not happen
text.setText(R.string.cache_list_unknown);
}
} else {
// hide box
box.setVisibility(View.GONE);
}
}
/**
* Handler, called when watchlist add or remove is done
*/
private class WatchlistHandler extends Handler {
@Override
public void handleMessage(Message msg) {
watchlistThread = null;
progress.dismiss();
if (msg.what == -1) {
showToast(res.getString(R.string.err_watchlist_failed));
} else {
CacheDetailActivity.this.notifyDataSetChanged(); // reload cache details
}
}
}
private class PreviewMapTask extends AsyncTask<Void, Void, BitmapDrawable> {
@Override
protected BitmapDrawable doInBackground(Void... parameters) {
try {
// persistent preview from storage
Bitmap image = decode(cache);
if (image == null) {
StaticMapsProvider.storeCachePreviewMap(cache);
image = decode(cache);
if (image == null) {
return null;
}
}
return ImageHelper.scaleBitmapToFitDisplay(image);
} catch (Exception e) {
Log.w("CacheDetailActivity.PreviewMapTask", e);
return null;
}
}
private Bitmap decode(final Geocache cache) {
return StaticMapsProvider.getPreviewMap(cache.getGeocode());
}
@Override
protected void onPostExecute(BitmapDrawable image) {
if (image == null) {
return;
}
try {
final Bitmap bitmap = image.getBitmap();
if (bitmap == null || bitmap.getWidth() <= 10) {
return;
}
((ImageView) view.findViewById(R.id.map_preview)).setImageDrawable(image);
view.findViewById(R.id.map_preview_box).setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("CacheDetailActivity.PreviewMapTask", e);
}
}
}
}
protected class DescriptionViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@InjectView(R.id.personalnote) protected TextView personalNoteView;
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_description, null);
Views.inject(this, view);
// cache short description
if (StringUtils.isNotBlank(cache.getShortDescription())) {
new LoadDescriptionTask(cache.getShortDescription(), view.findViewById(R.id.shortdesc), null, null).execute();
}
// long description
if (StringUtils.isNotBlank(cache.getDescription())) {
if (Settings.isAutoLoadDescription()) {
loadLongDescription();
} else {
Button showDesc = (Button) view.findViewById(R.id.show_description);
showDesc.setVisibility(View.VISIBLE);
showDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
loadLongDescription();
}
});
}
}
// cache personal note
setPersonalNote();
personalNoteView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
registerForContextMenu(personalNoteView);
final Button personalNoteEdit = (Button) view.findViewById(R.id.edit_personalnote);
personalNoteEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cache.isOffline()) {
editPersonalNote();
} else {
warnPersonalNoteNeedsStoring();
}
}
});
// cache hint and spoiler images
final View hintBoxView = view.findViewById(R.id.hint_box);
if (StringUtils.isNotBlank(cache.getHint()) || CollectionUtils.isNotEmpty(cache.getSpoilers())) {
hintBoxView.setVisibility(View.VISIBLE);
} else {
hintBoxView.setVisibility(View.GONE);
}
final TextView hintView = ((TextView) view.findViewById(R.id.hint));
if (StringUtils.isNotBlank(cache.getHint())) {
if (BaseUtils.containsHtml(cache.getHint())) {
hintView.setText(Html.fromHtml(cache.getHint(), new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null), TextView.BufferType.SPANNABLE);
hintView.setText(CryptUtils.rot13((Spannable) hintView.getText()));
}
else {
hintView.setText(CryptUtils.rot13(cache.getHint()));
}
hintView.setVisibility(View.VISIBLE);
hintView.setClickable(true);
hintView.setOnClickListener(new DecryptTextClickListener());
registerForContextMenu(hintView);
} else {
hintView.setVisibility(View.GONE);
hintView.setClickable(false);
hintView.setOnClickListener(null);
}
final TextView spoilerlinkView = ((TextView) view.findViewById(R.id.hint_spoilerlink));
if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
spoilerlinkView.setVisibility(View.VISIBLE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) {
showToast(res.getString(R.string.err_detail_no_spoiler));
return;
}
ImagesActivity.startActivitySpoilerImages(CacheDetailActivity.this, cache.getGeocode(), cache.getSpoilers());
}
});
} else {
spoilerlinkView.setVisibility(View.GONE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(null);
}
return view;
}
private void editPersonalNote() {
if (cache.isOffline()) {
editNoteDialogListener = new EditNoteDialogListener() {
@Override
public void onFinishEditNoteDialog(final String note) {
cache.setPersonalNote(note);
setPersonalNote();
cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
}
};
final FragmentManager fm = getSupportFragmentManager();
final EditNoteDialog dialog = EditNoteDialog.newInstance(cache.getPersonalNote());
dialog.show(fm, "fragment_edit_note");
}
}
private void setPersonalNote() {
final String personalNote = cache.getPersonalNote();
personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE);
if (StringUtils.isNotBlank(personalNote)) {
personalNoteView.setVisibility(View.VISIBLE);
} else {
personalNoteView.setVisibility(View.GONE);
}
}
private void loadLongDescription() {
Button showDesc = (Button) view.findViewById(R.id.show_description);
showDesc.setVisibility(View.GONE);
showDesc.setOnClickListener(null);
view.findViewById(R.id.loading).setVisibility(View.VISIBLE);
new LoadDescriptionTask(cache.getDescription(), view.findViewById(R.id.longdesc), view.findViewById(R.id.loading), view.findViewById(R.id.shortdesc)).execute();
}
private void warnPersonalNoteNeedsStoring() {
final AlertDialog.Builder builder = new AlertDialog.Builder(CacheDetailActivity.this);
builder.setTitle(R.string.cache_personal_note_unstored);
builder.setMessage(R.string.cache_personal_note_store);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
cache.store(null);
editPersonalNote();
}
});
final AlertDialog dialog = builder.create();
dialog.setOwnerActivity(CacheDetailActivity.this);
dialog.show();
}
}
@Override
public void onFinishEditNoteDialog(final String note) {
editNoteDialogListener.onFinishEditNoteDialog(note);
}
private static class HtmlImageCounter implements Html.ImageGetter {
private int imageCount = 0;
@Override
public Drawable getDrawable(String url) {
imageCount++;
return null;
}
public int getImageCount() {
return imageCount;
}
}
/**
* Loads the description in background. <br />
* <br />
* Params:
* <ol>
* <li>description string (String)</li>
* <li>target description view (TextView)</li>
* <li>loading indicator view (View, may be null)</li>
* </ol>
*/
private class LoadDescriptionTask extends AsyncTask<Object, Void, Void> {
private final View loadingIndicatorView;
private final TextView descriptionView;
private final String descriptionString;
private Spanned description;
private final View shortDescView;
public LoadDescriptionTask(final String description, final View descriptionView, final View loadingIndicatorView, final View shortDescView) {
this.descriptionString = description;
this.descriptionView = (TextView) descriptionView;
this.loadingIndicatorView = loadingIndicatorView;
this.shortDescView = shortDescView;
}
@Override
protected Void doInBackground(Object... params) {
try {
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
description = Html.fromHtml(descriptionString, imageCounter, unknownTagsHandler);
publishProgress();
boolean needsRefresh = false;
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
description = Html.fromHtml(descriptionString, new HtmlImage(cache.getGeocode(), true, cache.getListId(), false), unknownTagsHandler);
needsRefresh = true;
}
// If description has an HTML construct which may be problematic to render, add a note at the end of the long description.
// Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though
// sometimes technically incorrect.
if (unknownTagsHandler.isProblematicDetected() && descriptionView != null) {
final int startPos = description.length();
final IConnector connector = ConnectorFactory.getConnector(cache);
final Spanned tableNote = Html.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"));
((Editable) description).append("\n\n").append(tableNote);
((Editable) description).setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
needsRefresh = true;
}
if (needsRefresh) {
publishProgress();
}
} catch (Exception e) {
Log.e("LoadDescriptionTask: ", e);
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
if (description == null) {
showToast(res.getString(R.string.err_load_descr_failed));
return;
}
if (StringUtils.isNotBlank(descriptionString)) {
descriptionView.setText(description, TextView.BufferType.SPANNABLE);
descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
fixBlackTextColor(descriptionView, descriptionString);
descriptionView.setVisibility(View.VISIBLE);
registerForContextMenu(descriptionView);
hideDuplicatedShortDescription();
}
}
/**
* Hide the short description, if it is contained somewhere at the start of the long description.
*/
private void hideDuplicatedShortDescription() {
if (shortDescView != null) {
final String shortDescription = cache.getShortDescription();
if (StringUtils.isNotBlank(shortDescription)) {
int index = descriptionString.indexOf(shortDescription);
if (index >= 0 && index < 200) {
shortDescView.setVisibility(View.GONE);
}
}
}
}
@Override
protected void onPostExecute(Void result) {
if (null != loadingIndicatorView) {
loadingIndicatorView.setVisibility(View.GONE);
}
}
/**
* handle caches with black font color
*
* @param view
* @param text
*/
private void fixBlackTextColor(final TextView view, final String text) {
if (Settings.isLightSkin()) {
return;
}
int backcolor = color.black;
if (-1 != StringUtils.indexOfAny(text, new String[] { "color=\"black", "color=\"#000080\"" })) {
backcolor = color.darker_gray;
}
else {
MatcherWrapper matcher = new MatcherWrapper(DARK_COLOR_PATTERN, text);
if (matcher.find()) {
backcolor = color.darker_gray;
}
}
view.setBackgroundResource(backcolor);
}
}
private class LogsViewCreator extends AbstractCachingPageViewCreator<ListView> {
private final boolean allLogs;
LogsViewCreator(boolean allLogs) {
this.allLogs = allLogs;
}
@Override
public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_logs, null);
// log count
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (logCounts != null) {
final List<Entry<LogType, Integer>> sortedLogCounts = new ArrayList<Entry<LogType, Integer>>(logCounts.size());
for (Entry<LogType, Integer> entry : logCounts.entrySet()) {
// it may happen that the label is unknown -> then avoid any output for this type
if (entry.getKey() != LogType.PUBLISH_LISTING && entry.getKey().getL10n() != null) {
sortedLogCounts.add(entry);
}
}
if (!sortedLogCounts.isEmpty()) {
// sort the log counts by type id ascending. that way the FOUND, DNF log types are the first and most visible ones
Collections.sort(sortedLogCounts, new Comparator<Entry<LogType, Integer>>() {
@Override
public int compare(Entry<LogType, Integer> logCountItem1, Entry<LogType, Integer> logCountItem2) {
return logCountItem1.getKey().compareTo(logCountItem2.getKey());
}
});
ArrayList<String> labels = new ArrayList<String>(sortedLogCounts.size());
for (Entry<LogType, Integer> pair : sortedLogCounts) {
labels.add(pair.getValue() + "× " + pair.getKey().getL10n());
}
final TextView countView = new TextView(CacheDetailActivity.this);
countView.setText(res.getString(R.string.cache_log_types) + ": " + StringUtils.join(labels, ", "));
view.addHeaderView(countView, null, false);
}
}
final List<LogEntry> logs = allLogs ? cache.getLogs() : cache.getFriendsLogs();
view.setAdapter(new ArrayAdapter<LogEntry>(CacheDetailActivity.this, R.layout.cacheview_logs_item, logs) {
final UserActionsClickListener userActionsClickListener = new UserActionsClickListener();
final DecryptTextClickListener decryptTextClickListener = new DecryptTextClickListener();
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.cacheview_logs_item, null);
}
LogViewHolder holder = (LogViewHolder) rowView.getTag();
if (null == holder) {
holder = new LogViewHolder(rowView);
rowView.setTag(holder);
}
holder.setPosition(position);
final LogEntry log = getItem(position);
if (log.date > 0) {
holder.date.setText(Formatter.formatShortDate(log.date));
holder.date.setVisibility(View.VISIBLE);
} else {
holder.date.setVisibility(View.GONE);
}
holder.type.setText(log.type.getL10n());
holder.author.setText(StringEscapeUtils.unescapeHtml4(log.author));
// finds count
holder.count.setVisibility(View.VISIBLE);
if (log.found == -1) {
holder.count.setVisibility(View.GONE);
} else {
holder.count.setText(res.getQuantityString(R.plurals.cache_counts, log.found, log.found));
}
// logtext, avoid parsing HTML if not necessary
String logText = log.log;
if (BaseUtils.containsHtml(logText)) {
logText = log.getDisplayText();
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
- holder.text.setText(Html.fromHtml(logText, imageCounter, unknownTagsHandler));
+ holder.text.setText(Html.fromHtml(logText, imageCounter, unknownTagsHandler), TextView.BufferType.SPANNABLE);
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
LogImageLoader loader = new LogImageLoader(holder);
loader.execute(logText);
}
}
else {
- holder.text.setText(logText);
+ holder.text.setText(logText, TextView.BufferType.SPANNABLE);
}
// images
if (log.hasLogImages()) {
holder.images.setText(log.getImageTitles());
holder.images.setVisibility(View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagesActivity.startActivityLogImages(CacheDetailActivity.this, cache.getGeocode(), new ArrayList<Image>(log.getLogImages()));
}
});
} else {
holder.images.setVisibility(View.GONE);
}
// colored marker
int marker = log.type.markerId;
if (marker != 0) {
holder.statusMarker.setVisibility(View.VISIBLE);
holder.statusMarker.setImageResource(marker);
}
else {
holder.statusMarker.setVisibility(View.GONE);
}
if (null == convertView) {
// if convertView != null then this listeners are already set
holder.author.setOnClickListener(userActionsClickListener);
holder.text.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
holder.text.setOnClickListener(decryptTextClickListener);
registerForContextMenu(holder.text);
}
return rowView;
}
});
return view;
}
/** Loads the Log Images outside the ui thread. */
private class LogImageLoader extends AsyncTask<String, Progress, Spanned> {
final private LogViewHolder holder;
final private int position;
public LogImageLoader(LogViewHolder holder) {
this.holder = holder;
this.position = holder.getPosition();
}
@Override
protected Spanned doInBackground(String... logtext) {
return Html.fromHtml(logtext[0], new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null); //, TextView.BufferType.SPANNABLE)
}
@Override
protected void onPostExecute(Spanned result) {
// Ensure that this holder and its view still references the right item before updating the text.
if (position == holder.getPosition()) {
holder.text.setText(result);
}
}
}
private class LogViewHolder {
final TextView date;
final TextView type;
final TextView author;
final TextView count;
final TextView text;
final TextView images;
final ImageView statusMarker;
private int position;
public LogViewHolder(final View base) {
date = (TextView) base.findViewById(R.id.added);
type = (TextView) base.findViewById(R.id.type);
author = (TextView) base.findViewById(R.id.author);
count = (TextView) base.findViewById(R.id.count);
text = (TextView) base.findViewById(R.id.log);
images = (TextView) base.findViewById(R.id.log_images);
statusMarker = (ImageView) base.findViewById(R.id.log_mark);
}
/**
* Read the position of the cursor pointed to by this holder.
* <br/>
* This must be called by the UI thread.
*
* @return the cursor position
*/
public int getPosition() {
return position;
}
/**
* Set the position of the cursor pointed to by this holder.
* <br/>
* This must be called by the UI thread.
*
* @param position the cursor position
*/
public void setPosition(final int position) {
this.position = position;
}
}
}
private class WaypointsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@Override
public ScrollView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cacheview_waypoints, null);
final LinearLayout waypoints = (LinearLayout) view.findViewById(R.id.waypoints);
// sort waypoints: PP, Sx, FI, OWN
final List<Waypoint> sortedWaypoints = new ArrayList<Waypoint>(cache.getWaypoints());
Collections.sort(sortedWaypoints);
for (final Waypoint wpt : sortedWaypoints) {
final LinearLayout waypointView = (LinearLayout) getLayoutInflater().inflate(R.layout.waypoint_item, null);
// coordinates
if (null != wpt.getCoords()) {
final TextView coordinatesView = (TextView) waypointView.findViewById(R.id.coordinates);
coordinatesView.setOnClickListener(new CoordinatesFormatSwitcher(wpt.getCoords()));
coordinatesView.setText(wpt.getCoords().toString());
coordinatesView.setVisibility(View.VISIBLE);
}
// info
final String waypointInfo = Formatter.formatWaypointInfo(wpt);
if (StringUtils.isNotBlank(waypointInfo)) {
final TextView infoView = (TextView) waypointView.findViewById(R.id.info);
infoView.setText(waypointInfo);
infoView.setVisibility(View.VISIBLE);
}
// title
final TextView nameView = (TextView) waypointView.findViewById(R.id.name);
if (StringUtils.isNotBlank(wpt.getName())) {
nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.getName()));
} else if (null != wpt.getCoords()) {
nameView.setText(wpt.getCoords().toString());
} else {
nameView.setText(res.getString(R.string.waypoint));
}
wpt.setIcon(res, nameView);
// visited
if (wpt.isVisited()) {
TypedValue a = new TypedValue();
getTheme().resolveAttribute(R.attr.text_color_grey, a, true);
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// really should be just a color!
nameView.setTextColor(a.data);
}
}
// note
if (StringUtils.isNotBlank(wpt.getNote())) {
final TextView noteView = (TextView) waypointView.findViewById(R.id.note);
noteView.setVisibility(View.VISIBLE);
if (BaseUtils.containsHtml(wpt.getNote())) {
noteView.setText(Html.fromHtml(wpt.getNote()), TextView.BufferType.SPANNABLE);
}
else {
noteView.setText(wpt.getNote());
}
}
final View wpNavView = waypointView.findViewById(R.id.wpDefaultNavigation);
wpNavView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavigationAppFactory.startDefaultNavigationApplication(1, CacheDetailActivity.this, wpt);
}
});
wpNavView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
NavigationAppFactory.startDefaultNavigationApplication(2, CacheDetailActivity.this, wpt);
return true;
}
});
registerForContextMenu(waypointView);
waypointView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
waypoints.addView(waypointView);
}
final Button addWaypoint = (Button) view.findViewById(R.id.add_waypoint);
addWaypoint.setClickable(true);
addWaypoint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditWaypointActivity.startActivityAddWaypoint(CacheDetailActivity.this, cache);
refreshOnResume = true;
}
});
return view;
}
}
private class InventoryViewCreator extends AbstractCachingPageViewCreator<ListView> {
@Override
public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_inventory, null);
// TODO: fix layout, then switch back to Android-resource and delete copied one
// this copy is modified to respect the text color
view.setAdapter(new ArrayAdapter<Trackable>(CacheDetailActivity.this, R.layout.simple_list_item_1, cache.getInventory()));
view.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object selection = arg0.getItemAtPosition(arg2);
if (selection instanceof Trackable) {
Trackable trackable = (Trackable) selection;
TrackableActivity.startActivity(CacheDetailActivity.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName());
}
}
});
return view;
}
}
private class ImagesViewCreator extends AbstractCachingPageViewCreator<View> {
@Override
public View getDispatchedView() {
if (cache == null) {
return null; // something is really wrong
}
view = getLayoutInflater().inflate(R.layout.caches_images, null);
if (imagesList == null && isCurrentPage(Page.IMAGES)) {
loadCacheImages();
}
return view;
}
}
public static void startActivity(final Context context, final String geocode, final String cacheName) {
final Intent cachesIntent = new Intent(context, CacheDetailActivity.class);
cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cachesIntent);
}
public static void startActivityGuid(final Context context, final String guid, final String cacheName) {
final Intent cacheIntent = new Intent(context, CacheDetailActivity.class);
cacheIntent.putExtra(Intents.EXTRA_GUID, guid);
cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cacheIntent);
}
/**
* A dialog to allow the user to select reseting coordinates local/remote/both.
*/
private AlertDialog createResetCacheCoordinatesDialog(final Geocache cache, final Waypoint wpt) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.waypoint_reset_cache_coords);
String[] items = new String[] { res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords) };
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
dialog.dismiss();
final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1);
new ResetCoordsThread(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog).start();
}
});
return builder.create();
}
private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> {
private boolean remoteFinished = false;
private boolean localFinished = false;
private final ProgressDialog progressDialog;
private final boolean resetRemote;
protected HandlerResetCoordinates(CacheDetailActivity activity, ProgressDialog progressDialog, boolean resetRemote) {
super(activity);
this.progressDialog = progressDialog;
this.resetRemote = resetRemote;
}
@Override
public void handleMessage(Message msg) {
if (msg.what == ResetCoordsThread.LOCAL) {
localFinished = true;
} else {
remoteFinished = true;
}
if (localFinished && (remoteFinished || !resetRemote)) {
progressDialog.dismiss();
final CacheDetailActivity activity = getActivity();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
}
}
private class ResetCoordsThread extends Thread {
private final Geocache cache;
private final Handler handler;
private final boolean local;
private final boolean remote;
private final Waypoint wpt;
private ProgressDialog progress;
public static final int LOCAL = 0;
public static final int ON_WEBSITE = 1;
public ResetCoordsThread(Geocache cache, Handler handler, final Waypoint wpt, boolean local, boolean remote, final ProgressDialog progress) {
this.cache = cache;
this.handler = handler;
this.local = local;
this.remote = remote;
this.wpt = wpt;
this.progress = progress;
}
@Override
public void run() {
if (local) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords));
}
});
cache.setCoords(wpt.getCoords());
cache.setUserModifiedCoords(false);
cache.deleteWaypointForce(wpt);
cgData.saveChangedCache(cache);
handler.sendEmptyMessage(LOCAL);
}
IConnector con = ConnectorFactory.getConnector(cache);
if (remote && con.supportsOwnCoordinates()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website));
}
});
final boolean result = con.deleteModifiedCoordinates(cache);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (result) {
showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website));
} else {
showToast(getString(R.string.waypoint_coordinates_upload_error));
}
handler.sendEmptyMessage(ON_WEBSITE);
notifyDataSetChanged();
}
});
}
}
}
@Override
protected String getTitle(Page page) {
// show number of waypoints directly in waypoint title
if (page == Page.WAYPOINTS) {
final int waypointCount = cache.getWaypoints().size();
return res.getQuantityString(R.plurals.waypoints, waypointCount, waypointCount);
}
return res.getString(page.titleStringId);
}
@Override
protected Pair<List<? extends Page>, Integer> getOrderedPages() {
final ArrayList<Page> pages = new ArrayList<Page>();
pages.add(Page.WAYPOINTS);
pages.add(Page.DETAILS);
final int detailsIndex = pages.size() - 1;
pages.add(Page.DESCRIPTION);
if (!cache.getLogs().isEmpty()) {
pages.add(Page.LOGS);
}
if (CollectionUtils.isNotEmpty(cache.getFriendsLogs())) {
pages.add(Page.LOGSFRIENDS);
}
if (CollectionUtils.isNotEmpty(cache.getInventory())) {
pages.add(Page.INVENTORY);
}
if (CollectionUtils.isNotEmpty(cache.getImages())) {
pages.add(Page.IMAGES);
}
return new ImmutablePair<List<? extends Page>, Integer>(pages, detailsIndex);
}
@Override
protected AbstractViewPagerActivity.PageViewCreator createViewCreator(Page page) {
switch (page) {
case DETAILS:
return new DetailsViewCreator();
case DESCRIPTION:
return new DescriptionViewCreator();
case LOGS:
return new LogsViewCreator(true);
case LOGSFRIENDS:
return new LogsViewCreator(false);
case WAYPOINTS:
return new WaypointsViewCreator();
case INVENTORY:
return new InventoryViewCreator();
case IMAGES:
return new ImagesViewCreator();
default:
throw new IllegalArgumentException();
}
}
static void updateOfflineBox(final View view, final Geocache cache, final Resources res,
final OnClickListener refreshCacheClickListener,
final OnClickListener dropCacheClickListener,
final OnClickListener storeCacheClickListener) {
// offline use
final TextView offlineText = (TextView) view.findViewById(R.id.offline_text);
final Button offlineRefresh = (Button) view.findViewById(R.id.offline_refresh);
final Button offlineStore = (Button) view.findViewById(R.id.offline_store);
if (cache.isOffline()) {
long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes
String ago;
if (diff < 15) {
ago = res.getString(R.string.cache_offline_time_mins_few);
} else if (diff < 50) {
ago = res.getString(R.string.cache_offline_time_about) + " " + diff + " " + res.getString(R.string.cache_offline_time_mins);
} else if (diff < 90) {
ago = res.getString(R.string.cache_offline_time_about) + " " + res.getString(R.string.cache_offline_time_hour);
} else if (diff < (48 * 60)) {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / 60) + " " + res.getString(R.string.cache_offline_time_hours);
} else {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / (24 * 60)) + " " + res.getString(R.string.cache_offline_time_days);
}
offlineText.setText(res.getString(R.string.cache_offline_stored) + "\n" + ago);
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_drop));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(dropCacheClickListener);
} else {
offlineText.setText(res.getString(R.string.cache_offline_not_ready));
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_store));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(storeCacheClickListener);
}
offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE);
offlineRefresh.setClickable(true);
}
}
| false | true | public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_logs, null);
// log count
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (logCounts != null) {
final List<Entry<LogType, Integer>> sortedLogCounts = new ArrayList<Entry<LogType, Integer>>(logCounts.size());
for (Entry<LogType, Integer> entry : logCounts.entrySet()) {
// it may happen that the label is unknown -> then avoid any output for this type
if (entry.getKey() != LogType.PUBLISH_LISTING && entry.getKey().getL10n() != null) {
sortedLogCounts.add(entry);
}
}
if (!sortedLogCounts.isEmpty()) {
// sort the log counts by type id ascending. that way the FOUND, DNF log types are the first and most visible ones
Collections.sort(sortedLogCounts, new Comparator<Entry<LogType, Integer>>() {
@Override
public int compare(Entry<LogType, Integer> logCountItem1, Entry<LogType, Integer> logCountItem2) {
return logCountItem1.getKey().compareTo(logCountItem2.getKey());
}
});
ArrayList<String> labels = new ArrayList<String>(sortedLogCounts.size());
for (Entry<LogType, Integer> pair : sortedLogCounts) {
labels.add(pair.getValue() + "× " + pair.getKey().getL10n());
}
final TextView countView = new TextView(CacheDetailActivity.this);
countView.setText(res.getString(R.string.cache_log_types) + ": " + StringUtils.join(labels, ", "));
view.addHeaderView(countView, null, false);
}
}
final List<LogEntry> logs = allLogs ? cache.getLogs() : cache.getFriendsLogs();
view.setAdapter(new ArrayAdapter<LogEntry>(CacheDetailActivity.this, R.layout.cacheview_logs_item, logs) {
final UserActionsClickListener userActionsClickListener = new UserActionsClickListener();
final DecryptTextClickListener decryptTextClickListener = new DecryptTextClickListener();
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.cacheview_logs_item, null);
}
LogViewHolder holder = (LogViewHolder) rowView.getTag();
if (null == holder) {
holder = new LogViewHolder(rowView);
rowView.setTag(holder);
}
holder.setPosition(position);
final LogEntry log = getItem(position);
if (log.date > 0) {
holder.date.setText(Formatter.formatShortDate(log.date));
holder.date.setVisibility(View.VISIBLE);
} else {
holder.date.setVisibility(View.GONE);
}
holder.type.setText(log.type.getL10n());
holder.author.setText(StringEscapeUtils.unescapeHtml4(log.author));
// finds count
holder.count.setVisibility(View.VISIBLE);
if (log.found == -1) {
holder.count.setVisibility(View.GONE);
} else {
holder.count.setText(res.getQuantityString(R.plurals.cache_counts, log.found, log.found));
}
// logtext, avoid parsing HTML if not necessary
String logText = log.log;
if (BaseUtils.containsHtml(logText)) {
logText = log.getDisplayText();
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
holder.text.setText(Html.fromHtml(logText, imageCounter, unknownTagsHandler));
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
LogImageLoader loader = new LogImageLoader(holder);
loader.execute(logText);
}
}
else {
holder.text.setText(logText);
}
// images
if (log.hasLogImages()) {
holder.images.setText(log.getImageTitles());
holder.images.setVisibility(View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagesActivity.startActivityLogImages(CacheDetailActivity.this, cache.getGeocode(), new ArrayList<Image>(log.getLogImages()));
}
});
} else {
holder.images.setVisibility(View.GONE);
}
// colored marker
int marker = log.type.markerId;
if (marker != 0) {
holder.statusMarker.setVisibility(View.VISIBLE);
holder.statusMarker.setImageResource(marker);
}
else {
holder.statusMarker.setVisibility(View.GONE);
}
if (null == convertView) {
// if convertView != null then this listeners are already set
holder.author.setOnClickListener(userActionsClickListener);
holder.text.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
holder.text.setOnClickListener(decryptTextClickListener);
registerForContextMenu(holder.text);
}
return rowView;
}
});
return view;
}
| public ListView getDispatchedView() {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cacheview_logs, null);
// log count
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (logCounts != null) {
final List<Entry<LogType, Integer>> sortedLogCounts = new ArrayList<Entry<LogType, Integer>>(logCounts.size());
for (Entry<LogType, Integer> entry : logCounts.entrySet()) {
// it may happen that the label is unknown -> then avoid any output for this type
if (entry.getKey() != LogType.PUBLISH_LISTING && entry.getKey().getL10n() != null) {
sortedLogCounts.add(entry);
}
}
if (!sortedLogCounts.isEmpty()) {
// sort the log counts by type id ascending. that way the FOUND, DNF log types are the first and most visible ones
Collections.sort(sortedLogCounts, new Comparator<Entry<LogType, Integer>>() {
@Override
public int compare(Entry<LogType, Integer> logCountItem1, Entry<LogType, Integer> logCountItem2) {
return logCountItem1.getKey().compareTo(logCountItem2.getKey());
}
});
ArrayList<String> labels = new ArrayList<String>(sortedLogCounts.size());
for (Entry<LogType, Integer> pair : sortedLogCounts) {
labels.add(pair.getValue() + "× " + pair.getKey().getL10n());
}
final TextView countView = new TextView(CacheDetailActivity.this);
countView.setText(res.getString(R.string.cache_log_types) + ": " + StringUtils.join(labels, ", "));
view.addHeaderView(countView, null, false);
}
}
final List<LogEntry> logs = allLogs ? cache.getLogs() : cache.getFriendsLogs();
view.setAdapter(new ArrayAdapter<LogEntry>(CacheDetailActivity.this, R.layout.cacheview_logs_item, logs) {
final UserActionsClickListener userActionsClickListener = new UserActionsClickListener();
final DecryptTextClickListener decryptTextClickListener = new DecryptTextClickListener();
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.cacheview_logs_item, null);
}
LogViewHolder holder = (LogViewHolder) rowView.getTag();
if (null == holder) {
holder = new LogViewHolder(rowView);
rowView.setTag(holder);
}
holder.setPosition(position);
final LogEntry log = getItem(position);
if (log.date > 0) {
holder.date.setText(Formatter.formatShortDate(log.date));
holder.date.setVisibility(View.VISIBLE);
} else {
holder.date.setVisibility(View.GONE);
}
holder.type.setText(log.type.getL10n());
holder.author.setText(StringEscapeUtils.unescapeHtml4(log.author));
// finds count
holder.count.setVisibility(View.VISIBLE);
if (log.found == -1) {
holder.count.setVisibility(View.GONE);
} else {
holder.count.setText(res.getQuantityString(R.plurals.cache_counts, log.found, log.found));
}
// logtext, avoid parsing HTML if not necessary
String logText = log.log;
if (BaseUtils.containsHtml(logText)) {
logText = log.getDisplayText();
// Fast preview: parse only HTML without loading any images
HtmlImageCounter imageCounter = new HtmlImageCounter();
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
holder.text.setText(Html.fromHtml(logText, imageCounter, unknownTagsHandler), TextView.BufferType.SPANNABLE);
if (imageCounter.getImageCount() > 0) {
// Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview
LogImageLoader loader = new LogImageLoader(holder);
loader.execute(logText);
}
}
else {
holder.text.setText(logText, TextView.BufferType.SPANNABLE);
}
// images
if (log.hasLogImages()) {
holder.images.setText(log.getImageTitles());
holder.images.setVisibility(View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagesActivity.startActivityLogImages(CacheDetailActivity.this, cache.getGeocode(), new ArrayList<Image>(log.getLogImages()));
}
});
} else {
holder.images.setVisibility(View.GONE);
}
// colored marker
int marker = log.type.markerId;
if (marker != 0) {
holder.statusMarker.setVisibility(View.VISIBLE);
holder.statusMarker.setImageResource(marker);
}
else {
holder.statusMarker.setVisibility(View.GONE);
}
if (null == convertView) {
// if convertView != null then this listeners are already set
holder.author.setOnClickListener(userActionsClickListener);
holder.text.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
holder.text.setOnClickListener(decryptTextClickListener);
registerForContextMenu(holder.text);
}
return rowView;
}
});
return view;
}
|
diff --git a/server/plugins/eu.esdihumboldt.hale.server.templates.war/src/eu/esdihumboldt/hale/server/templates/war/components/UploadForm.java b/server/plugins/eu.esdihumboldt.hale.server.templates.war/src/eu/esdihumboldt/hale/server/templates/war/components/UploadForm.java
index 75a376a0c..0188e8542 100644
--- a/server/plugins/eu.esdihumboldt.hale.server.templates.war/src/eu/esdihumboldt/hale/server/templates/war/components/UploadForm.java
+++ b/server/plugins/eu.esdihumboldt.hale.server.templates.war/src/eu/esdihumboldt/hale/server/templates/war/components/UploadForm.java
@@ -1,238 +1,238 @@
/*
* Copyright (c) 2012 Data Harmonisation Panel
*
* All rights reserved. This program and the accompanying materials are made
* available 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Data Harmonisation Panel <http://www.dhpanel.eu>
*/
package eu.esdihumboldt.hale.server.templates.war.components;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.string.StringValue;
import org.apache.wicket.util.upload.FileUploadBase.SizeLimitExceededException;
import org.apache.wicket.util.upload.FileUploadException;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import com.google.common.io.ByteStreams;
import de.agilecoders.wicket.extensions.javascript.jasny.FileUploadField;
import de.cs3d.util.logging.ALogger;
import de.cs3d.util.logging.ALoggerFactory;
import eu.esdihumboldt.hale.common.core.io.project.ProjectInfo;
import eu.esdihumboldt.hale.common.headless.scavenger.ProjectReference;
import eu.esdihumboldt.hale.server.templates.TemplateScavenger;
import eu.esdihumboldt.hale.server.webapp.components.bootstrap.BootstrapFeedbackPanel;
import eu.esdihumboldt.util.Pair;
import eu.esdihumboldt.util.io.IOUtils;
import eu.esdihumboldt.util.scavenger.ScavengerException;
/**
* Upload form for new templates.
*
* @author Simon Templer
*/
public abstract class UploadForm extends Panel {
private static final long serialVersionUID = -8077630706189091706L;
private static final ALogger log = ALoggerFactory.getLogger(UploadForm.class);
private final FileUploadField file;
@SpringBean
private TemplateScavenger templates; // =
// OsgiUtils.getService(TemplateScavenger.class);
/**
* @see Panel#Panel(String)
*/
public UploadForm(String id) {
super(id);
Form<Void> form = new Form<Void>("upload") {
private static final long serialVersionUID = 716487990605324922L;
@Override
protected void onSubmit() {
// attempt to reserve template ID
Pair<String, File> template;
try {
template = templates.reserveResource(null);
} catch (ScavengerException e) {
error(e.getMessage());
return;
}
final String templateId = template.getFirst();
final File dir = template.getSecond();
try {
List<FileUpload> uploads = file.getFileUploads();
- if (!uploads.isEmpty()) {
+ if (uploads != null && !uploads.isEmpty()) {
for (FileUpload upload : uploads) {
if (isZipFile(upload)) {
// extract uploaded file
IOUtils.extract(dir,
new BufferedInputStream(upload.getInputStream()));
}
else {
// copy uploaded file
File target = new File(dir, upload.getClientFileName());
ByteStreams.copy(upload.getInputStream(), new FileOutputStream(
target));
}
}
// trigger scan after upload
templates.triggerScan();
ProjectReference<Void> ref = templates.getReference(templateId);
if (ref != null && ref.getProjectInfo() != null) {
info("Successfully uploaded project");
onUploadSuccess(this, templateId, ref.getProjectInfo());
}
else {
templates.releaseResourceId(templateId);
error("Uploaded files could not be loaded as HALE project");
}
}
else {
templates.releaseResourceId(templateId);
warn("Please provide a file for upload");
}
} catch (Exception e) {
templates.releaseResourceId(templateId);
log.error("Error while uploading file", e);
error("Error saving the file");
}
}
@Override
protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
if (e instanceof SizeLimitExceededException) {
final String msg = "Only files up to "
+ bytesToString(getMaxSize(), Locale.US) + " can be uploaded.";
error(msg);
}
else {
final String msg = "Error uploading the file: " + e.getLocalizedMessage();
error(msg);
log.warn(msg, e);
}
}
};
add(form);
// multipart always needed for uploads
form.setMultiPart(true);
// max size for upload
form.setMaxSize(Bytes.megabytes(1));
// Add file input field for multiple files
form.add(file = new FileUploadField("file"));
file.add(new IValidator<List<FileUpload>>() {
private static final long serialVersionUID = -5668788086384105101L;
@Override
public void validate(IValidatable<List<FileUpload>> validatable) {
if (validatable.getValue().isEmpty()) {
validatable.error(new ValidationError("No source files specified."));
}
}
});
form.add(new BootstrapFeedbackPanel("feedback"));
}
/**
* Determines if a file upload is a ZIP file.
*
* @param upload the file upload
* @return if the file upload is a ZIP file and should be extracted to the
* target directory
*/
protected boolean isZipFile(FileUpload upload) {
switch (upload.getContentType()) {
case "application/zip":
case "application/x-zip":
case "application/x-zip-compressed":
return true;
}
return upload.getClientFileName().toLowerCase().endsWith(".zip");
}
/**
* Called after a successful upload.
*
* @param form the form
* @param templateId the template identifier
* @param projectInfo the project info
*/
protected abstract void onUploadSuccess(Form<?> form, String templateId, ProjectInfo projectInfo);
/**
* Convert {@link Bytes} to a string, produces a prettier output than
* {@link Bytes#toString(Locale)}
*
* @param bytes the bytes
* @param locale the locale
*
* @return the converted string
*/
public static String bytesToString(Bytes bytes, Locale locale) {
if (bytes.bytes() >= 0) {
if (bytes.terabytes() >= 1.0) {
return unitString(bytes.terabytes(), "TB", locale);
}
if (bytes.gigabytes() >= 1.0) {
return unitString(bytes.gigabytes(), "GB", locale);
}
if (bytes.megabytes() >= 1.0) {
return unitString(bytes.megabytes(), "MB", locale);
}
if (bytes.kilobytes() >= 1.0) {
return unitString(bytes.kilobytes(), "KB", locale);
}
return Long.toString(bytes.bytes()) + " bytes";
}
else {
return "N/A";
}
}
private static String unitString(final double value, final String units, final Locale locale) {
return StringValue.valueOf(value, locale) + " " + units;
}
}
| true | true | public UploadForm(String id) {
super(id);
Form<Void> form = new Form<Void>("upload") {
private static final long serialVersionUID = 716487990605324922L;
@Override
protected void onSubmit() {
// attempt to reserve template ID
Pair<String, File> template;
try {
template = templates.reserveResource(null);
} catch (ScavengerException e) {
error(e.getMessage());
return;
}
final String templateId = template.getFirst();
final File dir = template.getSecond();
try {
List<FileUpload> uploads = file.getFileUploads();
if (!uploads.isEmpty()) {
for (FileUpload upload : uploads) {
if (isZipFile(upload)) {
// extract uploaded file
IOUtils.extract(dir,
new BufferedInputStream(upload.getInputStream()));
}
else {
// copy uploaded file
File target = new File(dir, upload.getClientFileName());
ByteStreams.copy(upload.getInputStream(), new FileOutputStream(
target));
}
}
// trigger scan after upload
templates.triggerScan();
ProjectReference<Void> ref = templates.getReference(templateId);
if (ref != null && ref.getProjectInfo() != null) {
info("Successfully uploaded project");
onUploadSuccess(this, templateId, ref.getProjectInfo());
}
else {
templates.releaseResourceId(templateId);
error("Uploaded files could not be loaded as HALE project");
}
}
else {
templates.releaseResourceId(templateId);
warn("Please provide a file for upload");
}
} catch (Exception e) {
templates.releaseResourceId(templateId);
log.error("Error while uploading file", e);
error("Error saving the file");
}
}
@Override
protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
if (e instanceof SizeLimitExceededException) {
final String msg = "Only files up to "
+ bytesToString(getMaxSize(), Locale.US) + " can be uploaded.";
error(msg);
}
else {
final String msg = "Error uploading the file: " + e.getLocalizedMessage();
error(msg);
log.warn(msg, e);
}
}
};
add(form);
// multipart always needed for uploads
form.setMultiPart(true);
// max size for upload
form.setMaxSize(Bytes.megabytes(1));
// Add file input field for multiple files
form.add(file = new FileUploadField("file"));
file.add(new IValidator<List<FileUpload>>() {
private static final long serialVersionUID = -5668788086384105101L;
@Override
public void validate(IValidatable<List<FileUpload>> validatable) {
if (validatable.getValue().isEmpty()) {
validatable.error(new ValidationError("No source files specified."));
}
}
});
form.add(new BootstrapFeedbackPanel("feedback"));
}
| public UploadForm(String id) {
super(id);
Form<Void> form = new Form<Void>("upload") {
private static final long serialVersionUID = 716487990605324922L;
@Override
protected void onSubmit() {
// attempt to reserve template ID
Pair<String, File> template;
try {
template = templates.reserveResource(null);
} catch (ScavengerException e) {
error(e.getMessage());
return;
}
final String templateId = template.getFirst();
final File dir = template.getSecond();
try {
List<FileUpload> uploads = file.getFileUploads();
if (uploads != null && !uploads.isEmpty()) {
for (FileUpload upload : uploads) {
if (isZipFile(upload)) {
// extract uploaded file
IOUtils.extract(dir,
new BufferedInputStream(upload.getInputStream()));
}
else {
// copy uploaded file
File target = new File(dir, upload.getClientFileName());
ByteStreams.copy(upload.getInputStream(), new FileOutputStream(
target));
}
}
// trigger scan after upload
templates.triggerScan();
ProjectReference<Void> ref = templates.getReference(templateId);
if (ref != null && ref.getProjectInfo() != null) {
info("Successfully uploaded project");
onUploadSuccess(this, templateId, ref.getProjectInfo());
}
else {
templates.releaseResourceId(templateId);
error("Uploaded files could not be loaded as HALE project");
}
}
else {
templates.releaseResourceId(templateId);
warn("Please provide a file for upload");
}
} catch (Exception e) {
templates.releaseResourceId(templateId);
log.error("Error while uploading file", e);
error("Error saving the file");
}
}
@Override
protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
if (e instanceof SizeLimitExceededException) {
final String msg = "Only files up to "
+ bytesToString(getMaxSize(), Locale.US) + " can be uploaded.";
error(msg);
}
else {
final String msg = "Error uploading the file: " + e.getLocalizedMessage();
error(msg);
log.warn(msg, e);
}
}
};
add(form);
// multipart always needed for uploads
form.setMultiPart(true);
// max size for upload
form.setMaxSize(Bytes.megabytes(1));
// Add file input field for multiple files
form.add(file = new FileUploadField("file"));
file.add(new IValidator<List<FileUpload>>() {
private static final long serialVersionUID = -5668788086384105101L;
@Override
public void validate(IValidatable<List<FileUpload>> validatable) {
if (validatable.getValue().isEmpty()) {
validatable.error(new ValidationError("No source files specified."));
}
}
});
form.add(new BootstrapFeedbackPanel("feedback"));
}
|
diff --git a/src/edu/berkeley/gamesman/database/cache/QuartoCache.java b/src/edu/berkeley/gamesman/database/cache/QuartoCache.java
index fc1d0d37..c5d2f920 100644
--- a/src/edu/berkeley/gamesman/database/cache/QuartoCache.java
+++ b/src/edu/berkeley/gamesman/database/cache/QuartoCache.java
@@ -1,181 +1,183 @@
package edu.berkeley.gamesman.database.cache;
import java.io.IOException;
import edu.berkeley.gamesman.core.Record;
import edu.berkeley.gamesman.database.Database;
import edu.berkeley.gamesman.database.DatabaseHandle;
import edu.berkeley.gamesman.game.Quarto;
import edu.berkeley.gamesman.game.util.TierState;
import edu.berkeley.gamesman.hasher.DartboardHasher;
import edu.berkeley.gamesman.hasher.QuartoMinorHasher;
public class QuartoCache extends TierCache {
private final RecordRangeCache[][] upperCaches = new RecordRangeCache[16][16];
private final RecordRangeCache[] lowerCache = new RecordRangeCache[16];
private final DartboardHasher majorHasher;
private final QuartoMinorHasher minorHasher;
private final Quarto game;
private final long cacheMemory;
private final DatabaseHandle dh;
public QuartoCache(Quarto game, DartboardHasher majorHasher,
QuartoMinorHasher minorHasher, Database db, long availableMemory) {
super(db, availableMemory);
this.game = game;
this.majorHasher = majorHasher;
this.minorHasher = minorHasher;
for (int place = 0; place < 16; place++) {
for (int pieceNum = 0; pieceNum < 16; pieceNum++) {
upperCaches[place][pieceNum] = new RecordRangeCache(db);
}
lowerCache[place] = upperCaches[place][0];
}
cacheMemory = availableMemory / 256;
dh = db.getHandle(true);
}
@Override
public void fetchChildren(TierState position, int numChildren,
TierState[] children, int[] hints, Record[] values) {
for (int child = 0; child < numChildren; child++) {
int piece = hints[child] / 16;
int place = hints[child] % 16;
long childHash = game.stateToHash(children[child]);
boolean childFetched = fetchChild(children[child], values[child],
piece, place, childHash);
if (!childFetched) {
setCache(place, piece);
childFetched = fetchChild(children[child], values[child],
piece, place, childHash);
assert childFetched;
}
}
}
private void setCache(int place, int piece) {
boolean success;
success = setCacheThroughAll(place, cacheMemory);
if (!success)
success = setCacheThrough(place, cacheMemory);
if (!success)
setCacheThrough(place, piece, cacheMemory);
}
private boolean fetchChild(TierState childState, Record toStore, int piece,
int place, long childHash) {
if (fetchChild(childState, lowerCache[place], childHash, toStore))
return true;
else if (fetchChild(childState, upperCaches[place][piece], childHash,
toStore))
return true;
else
return false;
}
private boolean fetchChild(TierState childState, RecordRangeCache cache,
long childHash, Record toStore) {
if (cache.containsRecord(childHash)) {
game.longToRecord(childState, cache.readRecord(childHash), toStore);
return true;
} else
return false;
}
private boolean setCacheThrough(int place, long availableMemory) {
int availableIntMemory = (int) Math.min(availableMemory,
Integer.MAX_VALUE);
int minorIndex = getMinorInsertionPlace(place);
long[] range = minorHasher.getCache(minorIndex,
db.recordsForBytes(availableIntMemory));
if (range == null)
return false;
else {
setCacheMinorRange(lowerCache[place], place, range[0],
(int) range[1], availableIntMemory);
return true;
}
}
private int getMinorInsertionPlace(int place) {
int nextFilled = place;
while (nextFilled < 16 && !game.placeList[nextFilled].hasPiece()) {
nextFilled++;
}
if (nextFilled >= 16)
return game.getTier();
else
return game.placeList[nextFilled].getMinorIndex();
}
private void setCacheMinorRange(RecordRangeCache cache, int place,
long minorRecordIndex, int numRecords, int ensureBytes) {
cache.ensureByteCapacity(ensureBytes, false);
long firstRecordIndex = game.hashOffsetForTier(game.getTier() + 1)
+ majorHasher.nextChild(' ', 'P', place)
* minorHasher.numHashesForTier(game.getTier() + 1)
+ minorRecordIndex;
cache.setRange(firstRecordIndex, numRecords);
try {
cache.readRecordsFromDatabase(db, dh, firstRecordIndex, numRecords);
} catch (IOException e) {
throw new Error(e);
}
}
private void setCacheMajorRange(RecordRangeCache cache, int place,
long majorRecordIndex, int numMajorPlaces, int ensureBytes) {
cache.ensureByteCapacity(ensureBytes, false);
long nextTierNumHashes = minorHasher
.numHashesForTier(game.getTier() + 1);
long firstRecordIndex = game.hashOffsetForTier(game.getTier() + 1)
+ majorRecordIndex * nextTierNumHashes;
int numRecords = (int) (numMajorPlaces * nextTierNumHashes);
cache.setRange(firstRecordIndex, numRecords);
try {
cache.readRecordsFromDatabase(db, dh, firstRecordIndex, numRecords);
} catch (IOException e) {
throw new Error(e);
}
}
private boolean setCacheThrough(int place, int piece, long availableMemory) {
int availableIntMemory = (int) Math.min(availableMemory,
Integer.MAX_VALUE);
int minorIndex = getMinorInsertionPlace(place);
long[] range = minorHasher.getCache(minorIndex, piece,
db.recordsForBytes(availableIntMemory));
if (range == null)
return false;
else {
setCacheMinorRange(upperCaches[place][piece], place, range[0],
(int) range[1], availableIntMemory);
return true;
}
}
private boolean setCacheThroughAll(int place, long availableMemory) {
int availableIntMemory = (int) Math.min(availableMemory,
Integer.MAX_VALUE);
long currentMajorChild = majorHasher.nextChild(' ', 'P', place);
int availableMajor = (int) (db.recordsForBytes(availableIntMemory) / minorHasher
.numHashesForTier());
if (availableMajor == 0)
return false;
else {
int addMajor = availableMajor * 2;
long lastMajorChild;
long majorHash = majorHasher.getHash();
+ long remainingMajor = majorHasher.numHashes() - majorHash;
+ addMajor = (int) Math.min(addMajor, remainingMajor);
do {
majorHasher.unhash(majorHash + addMajor - 1);
lastMajorChild = majorHasher.previousChild(' ', 'P', place);
addMajor /= 2;
} while (lastMajorChild - currentMajorChild + 1 > availableMajor);
majorHasher.unhash(majorHash);
setCacheMajorRange(lowerCache[place], place, currentMajorChild,
(int) (lastMajorChild - currentMajorChild + 1),
availableIntMemory);
return true;
}
}
}
| true | true | private boolean setCacheThroughAll(int place, long availableMemory) {
int availableIntMemory = (int) Math.min(availableMemory,
Integer.MAX_VALUE);
long currentMajorChild = majorHasher.nextChild(' ', 'P', place);
int availableMajor = (int) (db.recordsForBytes(availableIntMemory) / minorHasher
.numHashesForTier());
if (availableMajor == 0)
return false;
else {
int addMajor = availableMajor * 2;
long lastMajorChild;
long majorHash = majorHasher.getHash();
do {
majorHasher.unhash(majorHash + addMajor - 1);
lastMajorChild = majorHasher.previousChild(' ', 'P', place);
addMajor /= 2;
} while (lastMajorChild - currentMajorChild + 1 > availableMajor);
majorHasher.unhash(majorHash);
setCacheMajorRange(lowerCache[place], place, currentMajorChild,
(int) (lastMajorChild - currentMajorChild + 1),
availableIntMemory);
return true;
}
}
| private boolean setCacheThroughAll(int place, long availableMemory) {
int availableIntMemory = (int) Math.min(availableMemory,
Integer.MAX_VALUE);
long currentMajorChild = majorHasher.nextChild(' ', 'P', place);
int availableMajor = (int) (db.recordsForBytes(availableIntMemory) / minorHasher
.numHashesForTier());
if (availableMajor == 0)
return false;
else {
int addMajor = availableMajor * 2;
long lastMajorChild;
long majorHash = majorHasher.getHash();
long remainingMajor = majorHasher.numHashes() - majorHash;
addMajor = (int) Math.min(addMajor, remainingMajor);
do {
majorHasher.unhash(majorHash + addMajor - 1);
lastMajorChild = majorHasher.previousChild(' ', 'P', place);
addMajor /= 2;
} while (lastMajorChild - currentMajorChild + 1 > availableMajor);
majorHasher.unhash(majorHash);
setCacheMajorRange(lowerCache[place], place, currentMajorChild,
(int) (lastMajorChild - currentMajorChild + 1),
availableIntMemory);
return true;
}
}
|
diff --git a/src/servlets/Login.java b/src/servlets/Login.java
index e0f1b8f..fb55746 100644
--- a/src/servlets/Login.java
+++ b/src/servlets/Login.java
@@ -1,54 +1,54 @@
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.Database;
import entities.User;
/**
* Servlet implementation class Login
*/
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("pass");
User user = Database.getInstance().signIn(username, password);
if (user !=null){
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}else{
- response.sendRedirect("index.jsp?message=Wrong username and/or password! Or your registration is not approved yet!");
+ response.sendRedirect("index.jsp?message=2");
}
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("pass");
User user = Database.getInstance().signIn(username, password);
if (user !=null){
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}else{
response.sendRedirect("index.jsp?message=Wrong username and/or password! Or your registration is not approved yet!");
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("pass");
User user = Database.getInstance().signIn(username, password);
if (user !=null){
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}else{
response.sendRedirect("index.jsp?message=2");
}
}
|
diff --git a/src/main/java/com/edwardhand/mobrider/models/Ride.java b/src/main/java/com/edwardhand/mobrider/models/Ride.java
index 34c135b..355c5c4 100644
--- a/src/main/java/com/edwardhand/mobrider/models/Ride.java
+++ b/src/main/java/com/edwardhand/mobrider/models/Ride.java
@@ -1,408 +1,413 @@
package com.edwardhand.mobrider.models;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.entity.Creature;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.edwardhand.mobrider.MobRider;
import com.edwardhand.mobrider.utils.MRConfig;
import com.edwardhand.mobrider.utils.MRUtil;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityCreature;
import net.minecraft.server.EntitySquid;
import net.minecraft.server.PathEntity;
import net.minecraft.server.PathPoint;
public class Ride
{
public enum IntentType {
PASSIVE, FOLLOW, ATTACK, MOUNT, PAUSE, STOP;
}
private static final double ATTACK_RANGE = Math.pow(MRConfig.ATTACK_RANGE, 2.0D);
private static final double GOAL_RANGE = Math.pow(MRConfig.MOUNT_RANGE, 2.0D);
private static final int HEALTH_BARS = 6;
private Entity vehicle;
private BaseGoal goal;
private IntentType intent;
private float maxSpeed;
private float speed;
public Ride(Entity vehicle)
{
this.vehicle = vehicle;
if (vehicle != null) {
goal = new LocationGoal(getBukkitEntity().getLocation());
intent = IntentType.STOP;
if (isCreature() && MRUtil.getCreatureType(vehicle.getBukkitEntity()) != null) {
maxSpeed = RideType.fromType(MRUtil.getCreatureType(vehicle.getBukkitEntity())).getSpeed();
speed = maxSpeed;
}
else {
MobRider.getMRLogger().warning("Unknown creature " + vehicle);
}
}
}
public float getSpeed()
{
return Math.max(maxSpeed, speed * getMaxHealth() / getHealth());
}
public void setSpeed(float speed)
{
this.speed = Math.max(Math.min(speed, maxSpeed), 0.05F);
}
public Entity getRider()
{
return vehicle.passenger;
}
public org.bukkit.World getWorld()
{
return ((Creature) vehicle.getBukkitEntity()).getWorld();
}
public LivingEntity getTarget()
{
if (!isCreature())
return null;
return ((Creature) vehicle.getBukkitEntity()).getTarget();
}
public void setTarget(LivingEntity target)
{
if (!isCreature())
return;
((Creature) vehicle.getBukkitEntity()).setTarget(target);
}
public org.bukkit.entity.Entity getBukkitEntity()
{
return vehicle.getBukkitEntity();
}
public Boolean isValid()
{
return vehicle != null;
}
public Boolean isCreature()
{
return vehicle instanceof EntityCreature;
}
public Boolean isWaterCreature()
{
return vehicle instanceof EntitySquid;
}
public Boolean hasRider()
{
return (vehicle != null && vehicle.passenger != null && vehicle.passenger.vehicle != null);
}
public boolean hasGoal()
{
return goal != null;
}
public void resetGoal()
{
goal = null;
}
public void updateGoal()
{
if (!isCreature())
return;
if (hasGoal()) {
switch (intent) {
case ATTACK:
LivingEntity goalEntity = ((EntityGoal) goal).getEntity();
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goalEntity.getLocation()) > ATTACK_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
else {
setTarget(((EntityGoal) goal).getEntity());
}
break;
case FOLLOW:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE) {
setPathEntity(getBukkitEntity().getLocation());
intent = IntentType.PAUSE;
}
else {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
break;
case PAUSE:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) > GOAL_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
intent = IntentType.FOLLOW;
}
else {
setPathEntity(getBukkitEntity().getLocation());
}
break;
case MOUNT:
// TODO: do we need this case?
break;
case PASSIVE:
- if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE)
+ if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE) {
stop();
+ }
+ else {
+ setTarget(null);
+ setPathEntity(goal.getLocation());
+ }
break;
case STOP:
setTarget(null);
setPathEntity(((LocationGoal) goal).getLocation());
break;
}
updateSpeed();
}
}
public void attack(String entityName)
{
attack(findGoal(entityName));
}
public void attack(LivingEntity entity)
{
if (!isCreature())
return;
if (entity != null) {
goal = new EntityGoal(entity);
intent = IntentType.ATTACK;
speak(MRConfig.attackConfirmedMessage);
}
else {
speak(MRConfig.attackConfusedMessage);
}
}
public void follow(String entityName)
{
follow(findGoal(entityName));
}
public void follow(LivingEntity entity)
{
if (!isCreature())
return;
if (entity != null) {
goal = new EntityGoal(entity);
intent = IntentType.FOLLOW;
speak(MRConfig.followConfirmedMessage);
}
else {
speak(MRConfig.followConfusedMessage);
}
}
public void feed()
{
if (!isCreature())
return;
setHealth(Math.min(getHealth() + 5, getMaxHealth()));
speak(MRConfig.creatureFedMessage);
}
public void stop()
{
if (!isCreature())
return;
goal = new LocationGoal(getBukkitEntity().getLocation());
intent = IntentType.STOP;
speak(MRConfig.stopConfirmedMessage);
}
public void speak(String suffix)
{
if (!isCreature())
return;
Player player = (Player) getRider().getBukkitEntity();
player.sendMessage("<" + getHealthString(getBukkitEntity()) + "§e" + getCreatureType().getName() + "§f> " + getVehicleType().getNoise() + suffix);
}
public void setDirection(Vector direction)
{
setDirection(direction, MRConfig.MAX_TRAVEL_DISTANCE);
}
public void setDestination(Location location)
{
if (!isCreature())
return;
goal = new LocationGoal(location);
intent = IntentType.PASSIVE;
speak(MRConfig.goConfirmedMessage);
}
public void setDirection(Vector direction, int distance)
{
if (!isCreature())
return;
if (direction != null) {
goal = new LocationGoal(convertDirectionToLocation(direction.multiply(Math.min(2.5D, distance / MRConfig.MAX_TRAVEL_DISTANCE))));
intent = IntentType.PASSIVE;
speak(MRConfig.goConfirmedMessage);
}
else {
speak(MRConfig.goConfusedMessage);
}
}
private int getHealth()
{
int health = 0;
if (isCreature()) {
health = ((LivingEntity) vehicle.getBukkitEntity()).getHealth();
}
return health;
}
private int getMaxHealth()
{
int maxHealth = 0;
if (isCreature()) {
maxHealth = ((LivingEntity) vehicle.getBukkitEntity()).getMaxHealth();
}
return maxHealth;
}
private void setHealth(int health)
{
if (!isCreature())
return;
((LivingEntity) vehicle.getBukkitEntity()).setHealth(health);
}
private RideType getVehicleType()
{
return RideType.fromType(MRUtil.getCreatureType(vehicle.getBukkitEntity()));
}
private CreatureType getCreatureType()
{
return MRUtil.getCreatureType(vehicle.getBukkitEntity());
}
private LivingEntity findGoal(String searchTerm)
{
LivingEntity foundEntity = null;
// find entity by entity ID
if (MRUtil.isNumber(searchTerm)) {
Entity entity = ((CraftWorld) vehicle.getBukkitEntity().getWorld()).getHandle().getEntity(Integer.valueOf(searchTerm));
if (entity != null && entity instanceof LivingEntity) {
if (((LivingEntity) entity).getLocation().distanceSquared(vehicle.getBukkitEntity().getLocation()) < MRConfig.MAX_SEARCH_RANGE) {
foundEntity = (LivingEntity) entity;
}
}
}
// find player by name
else if (vehicle.getBukkitEntity().getServer().getPlayer(searchTerm) != null) {
foundEntity = vehicle.getBukkitEntity().getServer().getPlayer(searchTerm);
}
// find mob by name
else {
double lastDistance = Double.MAX_VALUE;
for (org.bukkit.entity.Entity entity : vehicle.getBukkitEntity().getNearbyEntities(2 * MRConfig.MAX_SEARCH_RANGE, 2 * MRConfig.MAX_SEARCH_RANGE, 2 * MRConfig.MAX_SEARCH_RANGE)) {
if (entity instanceof LivingEntity) {
CreatureType creatureType = MRUtil.getCreatureType(entity);
if (creatureType != null && creatureType.name().equalsIgnoreCase(searchTerm)) {
double entityDistance = vehicle.getBukkitEntity().getLocation().distanceSquared(entity.getLocation());
if (lastDistance > entityDistance && entity.getEntityId() != getRider().id) {
lastDistance = entityDistance;
foundEntity = (LivingEntity) entity;
}
}
}
}
}
return (LivingEntity) foundEntity;
}
private void updateSpeed()
{
if (!isCreature() || intent == IntentType.STOP || intent == IntentType.PAUSE) {
return;
}
CreatureType type = MRUtil.getCreatureType(vehicle.getBukkitEntity());
if (RideType.fromType(type) == null) {
return;
}
Vector velocity = vehicle.getBukkitEntity().getVelocity();
double saveY = velocity.getY();
velocity.normalize().multiply(getSpeed());
velocity.setY(saveY);
vehicle.getBukkitEntity().setVelocity(velocity);
}
private String getHealthString(org.bukkit.entity.Entity entity)
{
double percentHealth = (getHealth() * 100) / getMaxHealth();
ChatColor barColor;
if (percentHealth > 66) {
barColor = ChatColor.GREEN;
}
else if (percentHealth > 33) {
barColor = ChatColor.GOLD;
}
else {
barColor = ChatColor.RED;
}
StringBuilder healthString = new StringBuilder();
double colorSwitch = Math.ceil((percentHealth / 100D) * HEALTH_BARS);
for (int i = 0; i < HEALTH_BARS; i++) {
ChatColor color = i < colorSwitch ? barColor : ChatColor.GRAY;
healthString.append(color).append("|");
}
return healthString.toString();
}
private void setPathEntity(Location location)
{
((EntityCreature) vehicle).setPathEntity(new PathEntity(new PathPoint[] { new PathPoint(location.getBlockX(), location.getBlockY(), location.getBlockZ()) }));
}
private Location convertDirectionToLocation(Vector direction)
{
Location location = ((Creature) vehicle.getBukkitEntity()).getLocation();
return getWorld().getHighestBlockAt(location.getBlockX() + direction.getBlockX(), location.getBlockZ() + direction.getBlockZ()).getLocation();
}
}
| false | true | public void updateGoal()
{
if (!isCreature())
return;
if (hasGoal()) {
switch (intent) {
case ATTACK:
LivingEntity goalEntity = ((EntityGoal) goal).getEntity();
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goalEntity.getLocation()) > ATTACK_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
else {
setTarget(((EntityGoal) goal).getEntity());
}
break;
case FOLLOW:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE) {
setPathEntity(getBukkitEntity().getLocation());
intent = IntentType.PAUSE;
}
else {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
break;
case PAUSE:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) > GOAL_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
intent = IntentType.FOLLOW;
}
else {
setPathEntity(getBukkitEntity().getLocation());
}
break;
case MOUNT:
// TODO: do we need this case?
break;
case PASSIVE:
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE)
stop();
break;
case STOP:
setTarget(null);
setPathEntity(((LocationGoal) goal).getLocation());
break;
}
updateSpeed();
}
}
| public void updateGoal()
{
if (!isCreature())
return;
if (hasGoal()) {
switch (intent) {
case ATTACK:
LivingEntity goalEntity = ((EntityGoal) goal).getEntity();
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goalEntity.getLocation()) > ATTACK_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
else {
setTarget(((EntityGoal) goal).getEntity());
}
break;
case FOLLOW:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE) {
setPathEntity(getBukkitEntity().getLocation());
intent = IntentType.PAUSE;
}
else {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
}
break;
case PAUSE:
setTarget(null);
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) > GOAL_RANGE) {
setPathEntity(((EntityGoal) goal).getEntity().getLocation());
intent = IntentType.FOLLOW;
}
else {
setPathEntity(getBukkitEntity().getLocation());
}
break;
case MOUNT:
// TODO: do we need this case?
break;
case PASSIVE:
if (vehicle.getBukkitEntity().getLocation().distanceSquared(goal.getLocation()) < GOAL_RANGE) {
stop();
}
else {
setTarget(null);
setPathEntity(goal.getLocation());
}
break;
case STOP:
setTarget(null);
setPathEntity(((LocationGoal) goal).getLocation());
break;
}
updateSpeed();
}
}
|
diff --git a/src/org/racenet/framework/Polygon.java b/src/org/racenet/framework/Polygon.java
index 162e651..d821182 100755
--- a/src/org/racenet/framework/Polygon.java
+++ b/src/org/racenet/framework/Polygon.java
@@ -1,251 +1,251 @@
package org.racenet.framework;
/**
* Represents a polygon defined by at
* least three points
*
* @author soh#zolex
*/
public class Polygon {
public static final short TOP = 0;
public static final short LEFT = 1;
public static final short RAMPUP = 2;
public static final short RAMPDOWN = 3;
public static final short BOTTOM = 4;
/**
* The borders of the polygon represented by
* line segments
*/
public Vector2[] vertices;
public float width, height;
/**
* Structure which holds information about a collision
*
*/
public class CollisionInfo {
public boolean collided;
public short type;
public float distance;
}
/**
* Initialize a new polygon using multiple points
*
* @param Vector2 ... points
*/
public Polygon(Vector2 ... vertices) {
this.vertices = vertices;
this.calcWidth();
this.calcHeight();
}
/**
* Check if this polygon intersects with another one
*
* NOTE: This is a very simplified collision detection.
* "this" is always the player, an axis aligned rectangle.
* "other" my be a rectangular triangle or an axis aligned rectangle
*
* @param Polygon other
* @return boolean
*/
public CollisionInfo intersect(Polygon other){
CollisionInfo info = new CollisionInfo();
info.collided = false;
float thisX = this.getPosition().x;
float thisY = this.getPosition().y;
float otherX = other.getPosition().x;
float otherY = other.getPosition().y;
if (other.vertices.length == 4) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY + this.height > otherY && thisY + this.height < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
- float distanceY = otherY - thisY + this.height;
+ float distanceY = thisY + this.height - otherY;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = BOTTOM;
info.distance = distanceY;
}
info.collided = true;
return info;
}
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY > otherY && thisY < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
float distanceY = otherY + other.height - thisY;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = TOP;
info.distance = distanceY;
}
info.collided = true;
return info;
}
} else if (other.vertices.length == 3) {
// ramp up
if (other.vertices[1].x == other.vertices[2].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPUP;
return info;
}
}
// ramp down
if (other.vertices[0].x == other.vertices[1].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPDOWN;
return info;
}
}
}
return info;
}
public float getHeightAt(float x) {
if (this.vertices.length == 3) {
// ramp up
if (this.vertices[1].x == this.vertices[2].x) {
return (this.vertices[2].y - this.vertices[0].y) / (this.vertices[2].x - this.vertices[0].x) * (x - this.vertices[0].x);
}
// ramp down
if (this.vertices[0].x == this.vertices[1].x) {
return (this.vertices[0].y - this.vertices[2].y) / (this.vertices[0].x - this.vertices[2].x) * (x - this.vertices[2].x) - this.height;
}
}
return this.height;
}
/**
* Calculate the width of the polygon by determining
* the minimal and maximal x coordinates
*
* @return float
*/
public void calcWidth() {
float minX = 320000000;
float maxX = -320000000;
int length = this.vertices.length;
for (int i = 0; i < length; i++) {
if (this.vertices[i].x < minX) minX = this.vertices[i].x;
if (this.vertices[i].x > maxX) maxX = this.vertices[i].x;
}
this.width = maxX - minX;
}
/**
* Calculate the height of the polygon by determining
* the minimal and maximal x coordinates
*
* @return float
*/
public void calcHeight() {
float minY = 320000000;
float maxY = -320000000;
int length = this.vertices.length;
for (int i = 0; i < length; i++) {
if (this.vertices[i].y < minY) minY = this.vertices[i].y;
if (this.vertices[i].y > maxY) maxY = this.vertices[i].y;
}
this.height = maxY - minY;
}
/**
* TODO: for now just use the first given
* point as the position
*
* @return Vector2
*/
public Vector2 getPosition() {
return this.vertices[0];
}
/**
* Set the position by moving all borders
* of the polygon
*
* @param Vector2 position
*/
public void setPosition(Vector2 position) {
float diffX = position.x - this.getPosition().x;
float diffY = position.y - this.getPosition().y;
int length = this.vertices.length;
for (int i = 0; i < length; i++) {
this.vertices[i].x += diffX;
this.vertices[i].y += diffY;
}
}
/**
* Set the position by moving all borders
* of the polygon
*
* @param Vector2 position
*/
public void addToPosition(float x, float y) {
int length = this.vertices.length;
for (int i = 0; i < length; i++) {
this.vertices[i].x += x;
this.vertices[i].y += y;
}
}
}
| true | true | public CollisionInfo intersect(Polygon other){
CollisionInfo info = new CollisionInfo();
info.collided = false;
float thisX = this.getPosition().x;
float thisY = this.getPosition().y;
float otherX = other.getPosition().x;
float otherY = other.getPosition().y;
if (other.vertices.length == 4) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY + this.height > otherY && thisY + this.height < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
float distanceY = otherY - thisY + this.height;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = BOTTOM;
info.distance = distanceY;
}
info.collided = true;
return info;
}
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY > otherY && thisY < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
float distanceY = otherY + other.height - thisY;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = TOP;
info.distance = distanceY;
}
info.collided = true;
return info;
}
} else if (other.vertices.length == 3) {
// ramp up
if (other.vertices[1].x == other.vertices[2].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPUP;
return info;
}
}
// ramp down
if (other.vertices[0].x == other.vertices[1].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPDOWN;
return info;
}
}
}
return info;
}
| public CollisionInfo intersect(Polygon other){
CollisionInfo info = new CollisionInfo();
info.collided = false;
float thisX = this.getPosition().x;
float thisY = this.getPosition().y;
float otherX = other.getPosition().x;
float otherY = other.getPosition().y;
if (other.vertices.length == 4) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY + this.height > otherY && thisY + this.height < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
float distanceY = thisY + this.height - otherY;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = BOTTOM;
info.distance = distanceY;
}
info.collided = true;
return info;
}
if (thisX + this.width > otherX && thisX < otherX + other.width &&
thisY > otherY && thisY < otherY + otherHeight) {
float distanceX = thisX + this.width - otherX;
float distanceY = otherY + other.height - thisY;
if (distanceX < distanceY && other.height > this.height) {
info.type = LEFT;
info.distance = distanceX;
} else {
info.type = TOP;
info.distance = distanceY;
}
info.collided = true;
return info;
}
} else if (other.vertices.length == 3) {
// ramp up
if (other.vertices[1].x == other.vertices[2].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPUP;
return info;
}
}
// ramp down
if (other.vertices[0].x == other.vertices[1].x) {
float otherHeight = other.getHeightAt(thisX);
if (thisX + this.width > otherX && thisX < otherX + other.width && thisY <= otherY + otherHeight) {
info.collided = true;
info.distance = 0;
info.type = RAMPDOWN;
return info;
}
}
}
return info;
}
|
diff --git a/src/org/key2gym/business/FreezesService.java b/src/org/key2gym/business/FreezesService.java
index d64bdcd..d09a546 100644
--- a/src/org/key2gym/business/FreezesService.java
+++ b/src/org/key2gym/business/FreezesService.java
@@ -1,325 +1,325 @@
/*
* Copyright 2012 Danylo Vashchilenko
*
* 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.key2gym.business;
import java.text.MessageFormat;
import org.key2gym.business.api.BusinessException;
import org.key2gym.business.api.SecurityException;
import org.key2gym.business.api.ValidationException;
import org.key2gym.business.dto.FreezeDTO;
import org.key2gym.persistence.Administrator;
import org.key2gym.persistence.Client;
import org.key2gym.persistence.ClientFreeze;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.joda.time.DateMidnight;
import org.omg.CORBA.INTERNAL;
/**
*
* @author Danylo Vashchilenko
*/
public class FreezesService extends BusinessService {
protected FreezesService() {
}
/**
* Records a freeze for the client.
*
* <ul>
*
* <li> The current permissions level has to be at least
* <code>PL_EXTENDED</code>. </li> <li> The client can not be expired. </li>
* <li> The number of days can not exceed 10. </li> <li> There can be at
* most 1 freeze per month. </li>
*
* </ul>
*
* @param clientId the client's ID
* @throws IllegalStateException if the transaction or the session is not
* active
* @throws NullPointerException if any of the arguments is null
* @throws ValidationException if the client's ID is invalid
* @throws BusinessException if current business rules restrict this
* operation
* @throws SecurityException if current security rules restrict this
* operation
*/
public void addFreeze(Short clientId, Short days, String note) throws ValidationException, BusinessException, org.key2gym.business.api.SecurityException {
assertOpenSessionExists();
assertTransactionActive();
if (clientId == null) {
throw new NullPointerException("The clientId is null."); //NOI18N
}
if (days == null) {
throw new NullPointerException("The days is null."); //NOI18N
}
if (note == null) {
throw new NullPointerException("The note is null."); //NOI18N
}
if (sessionService.getPermissionsLevel() > SessionsService.PL_EXTENDED) {
throw new SecurityException(bundle.getString("Security.Operation.Denied"));
}
Client client = entityManager.find(Client.class, clientId);
if (client == null) {
throw new ValidationException(bundle.getString("Invalid.Client.ID"));
}
if (client.getExpirationDate().compareTo(new Date()) < 0) {
throw new BusinessException(bundle.getString("BusinessRule.Client.SubscriptionExpired"));
}
if (days < 1 || days > 10) {
String message = MessageFormat.format(
bundle.getString("BusinessRule.Freeze.Days.HasToBeWithinRange.withRangeBeginAndRangeEnd"),
- new Integer[]{1, 10}
+ 1, 10
);
throw new ValidationException(message);
}
if (note.trim().isEmpty()) {
throw new ValidationException(bundle.getString("Invalid.Freeze.Note.CanNotBeEmpty"));
}
DateMidnight today = new DateMidnight();
List<ClientFreeze> freezes = entityManager
.createNamedQuery("ClientFreeze.findByClientAndDateIssuedRange") //NOI18N
.setParameter("client", client)
.setParameter("rangeBegin", today.minusMonths(1).toDate()) //NOI18N
.setParameter("rangeEnd", today.toDate()) //NOI18N
.getResultList();
if (!freezes.isEmpty()) {
throw new BusinessException(bundle.getString("BusinessRule.Freeze.ClientHasAlreadyBeenFrozenLastMonth"));
}
// Rolls the expiration date
client.setExpirationDate(new DateMidnight(client.getExpirationDate()).plusDays(days).toDate());
ClientFreeze clientFreeze = new ClientFreeze();
clientFreeze.setDateIssued(new Date());
clientFreeze.setDays(days);
clientFreeze.setClient(client);
clientFreeze.setAdministrator(entityManager.find(Administrator.class, sessionService.getTopmostAdministratorId()));
clientFreeze.setNote(note);
entityManager.persist(clientFreeze);
entityManager.flush();
}
/**
* Finds all freezes for the client.
*
* @param clientId the client's ID
* @throws IllegalStateException if the session is not active
* @throws NullPointerException if the client's ID is null
* @throws ValidationException if the client's ID is invalid
* @return the list of all freezes for the client
*/
public List<FreezeDTO> findFreezesForClient(Short clientId) throws ValidationException {
assertOpenSessionExists();
if (clientId == null) {
throw new NullPointerException("The clientId is null."); //NOI18N
}
Client client = entityManager.find(Client.class, clientId);
if (client == null) {
throw new ValidationException(bundle.getString("Invalid.Client.ID"));
}
List<ClientFreeze> freezes = entityManager.createNamedQuery("ClientFreeze.findByClient").setParameter("client", client).getResultList(); //NOI18N
List<FreezeDTO> result = new LinkedList<>();
for (ClientFreeze freeze : freezes) {
result.add(wrapFreeze(freeze));
}
return result;
}
/**
* Finds freezes having date issued within the range.
*
* <ul>
*
* <li> The permissions level has to be PL_ALL </li>
* <li> The beginning date has be before or equal to ending date. </li>
*
* </ul>
*
* @param begin the beginning date
* @param end the ending date
* @return the list of freezes
* @throws IllegalStateException if no session is open
* @throws NullPointerException if any of the arguments is null
* @throws SecurityException if current security rules restrict this operation
* @throws BusinessException if any of the arguments is invalid
*/
public List<FreezeDTO> findByDateIssuedRange(DateMidnight begin, DateMidnight end) throws SecurityException, ValidationException {
assertOpenSessionExists();
if(!sessionService.getPermissionsLevel().equals(SessionsService.PL_ALL)) {
throw new SecurityException(bundle.getString("Security.Access.Denied"));
}
if(begin == null) {
throw new NullPointerException("The begin is null."); //NOI18N
}
if(end == null) {
throw new NullPointerException("The end is null."); //NOI18N
}
if(begin.isAfter(end)) {
throw new ValidationException(bundle.getString("Invalid.DateRange.BeginningAfterEnding"));
}
List<ClientFreeze> freezes = entityManager
.createNamedQuery("ClientFreeze.findByDateIssuedRange") //NOI18N
.setParameter("rangeBegin", begin.toDate()) //NOI18N
.setParameter("rangeEnd", end.toDate()) //NOI18N
.getResultList();
List<FreezeDTO> result = new LinkedList<>();
for(ClientFreeze freeze : freezes) {
result.add(wrapFreeze(freeze));
}
return result;
}
/**
* Finds all freezes.
*
* <ul>
*
* <li> The permissions level has to be PL_ALL. </li>
*
* </ul>
*
* @throws IllegalStateException if no session is open
* @throws SecurityException if current security rules restrict this operation
* @return the list of all freezes
*/
public List<FreezeDTO> findAll() {
assertOpenSessionExists();
List<ClientFreeze> freezes = entityManager
.createNamedQuery("ClientFreeze.findAll") //NOI18N
.getResultList();
List<FreezeDTO> result = new LinkedList<>();
for(ClientFreeze freeze : freezes) {
result.add(wrapFreeze(freeze));
}
return result;
}
/**
* Removes the freeze by its ID.
*
* <ul>
*
* <li> The permissions level has to be PL_ALL </li>
* <li> The freeze has to be active, which is the expiration date can
* not be in the past. </li>
*
* </ul>
*
* @param id the freeze's ID
* @throws IllegalStateException if no session is open
* @throws SecurityException if current security rules restrict this operation
* @throws NullPointerException if the freeze's ID is null
* @throws ValidationException if the freeze's ID is invalid
* @throws BusinessException if current business rules restrict this operation
*/
public void remove(Short id) throws SecurityException, ValidationException, BusinessException {
assertOpenSessionExists();
if(!sessionService.getPermissionsLevel().equals(SessionsService.PL_ALL)) {
throw new SecurityException(bundle.getString("Security.Operation.Denied"));
}
assertTransactionActive();
if(id == null) {
throw new NullPointerException("The id is null."); //NOI18N
}
ClientFreeze clientFreeze = entityManager.find(ClientFreeze.class, id);
if(clientFreeze == null) {
throw new ValidationException(bundle.getString("Invalid.Freeze.ID"));
}
if(new DateMidnight(clientFreeze.getDateIssued()).plusDays(clientFreeze.getDays()).isBeforeNow()) {
throw new BusinessException(bundle.getString("BusinessRule.Freeze.AlreadyExpired"));
}
Client client = clientFreeze.getClient();
client.setExpirationDate(new DateMidnight(client.getExpirationDate()).minusDays(clientFreeze.getDays()).toDate());
// TODO: note change
entityManager.remove(clientFreeze);
entityManager.flush();
}
private FreezeDTO wrapFreeze(ClientFreeze freeze) {
FreezeDTO freezeDTO = new FreezeDTO();
freezeDTO.setId(freeze.getId());
freezeDTO.setAdministratorFullName(freeze.getAdministrator().getFullName());
freezeDTO.setAdministratorId(freeze.getAdministrator().getId());
freezeDTO.setClientFullName(freeze.getClient().getFullName());
freezeDTO.setClientId(freeze.getClient().getId());
freezeDTO.setDateIssued(new DateMidnight(freeze.getDateIssued()));
freezeDTO.setDays(freeze.getDays());
freezeDTO.setNote(freeze.getNote());
return freezeDTO;
}
/**
* Singleton instance.
*/
private static FreezesService instance;
/**
* Gets an instance of this class.
*
* @return an instance of this class
*/
public static FreezesService getInstance() {
if (instance == null) {
instance = new FreezesService();
}
return instance;
}
}
| true | true | public void addFreeze(Short clientId, Short days, String note) throws ValidationException, BusinessException, org.key2gym.business.api.SecurityException {
assertOpenSessionExists();
assertTransactionActive();
if (clientId == null) {
throw new NullPointerException("The clientId is null."); //NOI18N
}
if (days == null) {
throw new NullPointerException("The days is null."); //NOI18N
}
if (note == null) {
throw new NullPointerException("The note is null."); //NOI18N
}
if (sessionService.getPermissionsLevel() > SessionsService.PL_EXTENDED) {
throw new SecurityException(bundle.getString("Security.Operation.Denied"));
}
Client client = entityManager.find(Client.class, clientId);
if (client == null) {
throw new ValidationException(bundle.getString("Invalid.Client.ID"));
}
if (client.getExpirationDate().compareTo(new Date()) < 0) {
throw new BusinessException(bundle.getString("BusinessRule.Client.SubscriptionExpired"));
}
if (days < 1 || days > 10) {
String message = MessageFormat.format(
bundle.getString("BusinessRule.Freeze.Days.HasToBeWithinRange.withRangeBeginAndRangeEnd"),
new Integer[]{1, 10}
);
throw new ValidationException(message);
}
if (note.trim().isEmpty()) {
throw new ValidationException(bundle.getString("Invalid.Freeze.Note.CanNotBeEmpty"));
}
DateMidnight today = new DateMidnight();
List<ClientFreeze> freezes = entityManager
.createNamedQuery("ClientFreeze.findByClientAndDateIssuedRange") //NOI18N
.setParameter("client", client)
.setParameter("rangeBegin", today.minusMonths(1).toDate()) //NOI18N
.setParameter("rangeEnd", today.toDate()) //NOI18N
.getResultList();
if (!freezes.isEmpty()) {
throw new BusinessException(bundle.getString("BusinessRule.Freeze.ClientHasAlreadyBeenFrozenLastMonth"));
}
// Rolls the expiration date
client.setExpirationDate(new DateMidnight(client.getExpirationDate()).plusDays(days).toDate());
ClientFreeze clientFreeze = new ClientFreeze();
clientFreeze.setDateIssued(new Date());
clientFreeze.setDays(days);
clientFreeze.setClient(client);
clientFreeze.setAdministrator(entityManager.find(Administrator.class, sessionService.getTopmostAdministratorId()));
clientFreeze.setNote(note);
entityManager.persist(clientFreeze);
entityManager.flush();
}
| public void addFreeze(Short clientId, Short days, String note) throws ValidationException, BusinessException, org.key2gym.business.api.SecurityException {
assertOpenSessionExists();
assertTransactionActive();
if (clientId == null) {
throw new NullPointerException("The clientId is null."); //NOI18N
}
if (days == null) {
throw new NullPointerException("The days is null."); //NOI18N
}
if (note == null) {
throw new NullPointerException("The note is null."); //NOI18N
}
if (sessionService.getPermissionsLevel() > SessionsService.PL_EXTENDED) {
throw new SecurityException(bundle.getString("Security.Operation.Denied"));
}
Client client = entityManager.find(Client.class, clientId);
if (client == null) {
throw new ValidationException(bundle.getString("Invalid.Client.ID"));
}
if (client.getExpirationDate().compareTo(new Date()) < 0) {
throw new BusinessException(bundle.getString("BusinessRule.Client.SubscriptionExpired"));
}
if (days < 1 || days > 10) {
String message = MessageFormat.format(
bundle.getString("BusinessRule.Freeze.Days.HasToBeWithinRange.withRangeBeginAndRangeEnd"),
1, 10
);
throw new ValidationException(message);
}
if (note.trim().isEmpty()) {
throw new ValidationException(bundle.getString("Invalid.Freeze.Note.CanNotBeEmpty"));
}
DateMidnight today = new DateMidnight();
List<ClientFreeze> freezes = entityManager
.createNamedQuery("ClientFreeze.findByClientAndDateIssuedRange") //NOI18N
.setParameter("client", client)
.setParameter("rangeBegin", today.minusMonths(1).toDate()) //NOI18N
.setParameter("rangeEnd", today.toDate()) //NOI18N
.getResultList();
if (!freezes.isEmpty()) {
throw new BusinessException(bundle.getString("BusinessRule.Freeze.ClientHasAlreadyBeenFrozenLastMonth"));
}
// Rolls the expiration date
client.setExpirationDate(new DateMidnight(client.getExpirationDate()).plusDays(days).toDate());
ClientFreeze clientFreeze = new ClientFreeze();
clientFreeze.setDateIssued(new Date());
clientFreeze.setDays(days);
clientFreeze.setClient(client);
clientFreeze.setAdministrator(entityManager.find(Administrator.class, sessionService.getTopmostAdministratorId()));
clientFreeze.setNote(note);
entityManager.persist(clientFreeze);
entityManager.flush();
}
|
diff --git a/openstreetmap/src/main/java/org/opentripplanner/openstreetmap/model/OSMLevel.java b/openstreetmap/src/main/java/org/opentripplanner/openstreetmap/model/OSMLevel.java
index 7db039252..62533078b 100644
--- a/openstreetmap/src/main/java/org/opentripplanner/openstreetmap/model/OSMLevel.java
+++ b/openstreetmap/src/main/java/org/opentripplanner/openstreetmap/model/OSMLevel.java
@@ -1,176 +1,182 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.openstreetmap.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OSMLevel implements Comparable<OSMLevel> {
private static Logger _log = LoggerFactory.getLogger(OSMLevel.class);
public static final Pattern RANGE_PATTERN = Pattern.compile("^[0-9]+\\-[0-9]+$");
public static final double METERS_PER_FLOOR = 3;
public static final OSMLevel DEFAULT =
new OSMLevel(0, 0.0, "default level", "default level", Source.NONE, true);
public final int floorNumber; // 0-based
public final double altitudeMeters;
public final String shortName; // localized (potentially 1-based)
public final String longName; // localized (potentially 1-based)
public final Source source;
public final boolean reliable;
public enum Source {
LEVEL_MAP,
LEVEL_TAG,
LAYER_TAG,
ALTITUDE,
NONE
}
public OSMLevel(int floorNumber, double altitudeMeters, String shortName, String longName,
Source source, boolean reliable) {
this.floorNumber = floorNumber;
this.altitudeMeters = altitudeMeters;
this.shortName = shortName;
this.longName = longName;
this.source = source;
this.reliable = reliable;
}
/**
* makes an OSMLevel from one of the semicolon-separated fields in an OSM
* level map relation's levels= tag.
*/
public static OSMLevel fromString (String spec, Source source, boolean incrementNonNegative) {
/* extract any altitude information after the @ character */
Double altitude = null;
boolean reliable = true;
int lastIndexAt = spec.lastIndexOf('@');
if (lastIndexAt != -1) {
try {
altitude = Double.parseDouble(spec.substring(lastIndexAt + 1));
} catch (NumberFormatException e) {}
spec = spec.substring(0, lastIndexAt);
}
/* get short and long level names by splitting on = character */
String shortName = "";
String longName = "";
Integer indexEquals = spec.indexOf('=');
if (indexEquals >= 1) {
shortName = spec.substring(0, indexEquals);
longName = spec.substring(indexEquals + 1);
} else {
// set them both the same, the trailing @altitude has already been discarded
shortName = longName = spec;
}
+ if (longName.startsWith("+")) {
+ longName = longName.substring(1);
+ }
+ if (shortName.startsWith("+")) {
+ shortName = shortName.substring(1);
+ }
/* try to parse a floor number out of names */
Integer floorNumber = null;
try {
floorNumber = Integer.parseInt(longName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
longName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
try {
// short name takes precedence over long name for floor numbering
floorNumber = Integer.parseInt(shortName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
shortName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
/* fall back on altitude when necessary */
if (floorNumber == null && altitude != null) {
floorNumber = (int)(altitude / METERS_PER_FLOOR);
_log.warn("Could not determine floor number for layer {}. Guessed {} (0-based) from altitude.", spec, floorNumber);
reliable = false;
}
/* set default value if parsing failed */
if (altitude == null) {
altitude = 0.0;
}
/* signal failure to extract any useful level information */
if (floorNumber == null) {
floorNumber = 0;
_log.warn("Could not determine floor number for layer {}, assumed to be ground-level.",
spec, floorNumber);
reliable = false;
}
return new OSMLevel(floorNumber, altitude, shortName, longName, source, reliable);
}
public static List<OSMLevel> fromSpecList (String specList, Source source, boolean incrementNonNegative) {
List<String> levelSpecs = new ArrayList<String>();
Matcher m;
for (String level : specList.split(";")) {
m = RANGE_PATTERN.matcher(level);
if (m.matches()) { // this field specifies a range of levels
String[] range = level.split("-");
int endOfRange = Integer.parseInt(range[1]);
for (int i = Integer.parseInt(range[0]); i <= endOfRange; i++) {
levelSpecs.add(Integer.toString(i));
}
} else { // this field is not a range, just a single level
levelSpecs.add(level);
}
}
/* build an OSMLevel for each level spec in the list */
List<OSMLevel> levels = new ArrayList<OSMLevel>();
for (String spec : levelSpecs) {
levels.add(fromString(spec, source, incrementNonNegative));
}
return levels;
}
public static Map<String, OSMLevel> mapFromSpecList (String specList, Source source, boolean incrementNonNegative) {
Map<String, OSMLevel> map = new HashMap<String, OSMLevel>();
for (OSMLevel level : fromSpecList(specList, source, incrementNonNegative)) {
map.put(level.shortName, level);
}
return map;
}
@Override
public int compareTo(OSMLevel other) {
return this.floorNumber - other.floorNumber;
}
}
| true | true | public static OSMLevel fromString (String spec, Source source, boolean incrementNonNegative) {
/* extract any altitude information after the @ character */
Double altitude = null;
boolean reliable = true;
int lastIndexAt = spec.lastIndexOf('@');
if (lastIndexAt != -1) {
try {
altitude = Double.parseDouble(spec.substring(lastIndexAt + 1));
} catch (NumberFormatException e) {}
spec = spec.substring(0, lastIndexAt);
}
/* get short and long level names by splitting on = character */
String shortName = "";
String longName = "";
Integer indexEquals = spec.indexOf('=');
if (indexEquals >= 1) {
shortName = spec.substring(0, indexEquals);
longName = spec.substring(indexEquals + 1);
} else {
// set them both the same, the trailing @altitude has already been discarded
shortName = longName = spec;
}
/* try to parse a floor number out of names */
Integer floorNumber = null;
try {
floorNumber = Integer.parseInt(longName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
longName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
try {
// short name takes precedence over long name for floor numbering
floorNumber = Integer.parseInt(shortName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
shortName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
/* fall back on altitude when necessary */
if (floorNumber == null && altitude != null) {
floorNumber = (int)(altitude / METERS_PER_FLOOR);
_log.warn("Could not determine floor number for layer {}. Guessed {} (0-based) from altitude.", spec, floorNumber);
reliable = false;
}
/* set default value if parsing failed */
if (altitude == null) {
altitude = 0.0;
}
/* signal failure to extract any useful level information */
if (floorNumber == null) {
floorNumber = 0;
_log.warn("Could not determine floor number for layer {}, assumed to be ground-level.",
spec, floorNumber);
reliable = false;
}
return new OSMLevel(floorNumber, altitude, shortName, longName, source, reliable);
}
| public static OSMLevel fromString (String spec, Source source, boolean incrementNonNegative) {
/* extract any altitude information after the @ character */
Double altitude = null;
boolean reliable = true;
int lastIndexAt = spec.lastIndexOf('@');
if (lastIndexAt != -1) {
try {
altitude = Double.parseDouble(spec.substring(lastIndexAt + 1));
} catch (NumberFormatException e) {}
spec = spec.substring(0, lastIndexAt);
}
/* get short and long level names by splitting on = character */
String shortName = "";
String longName = "";
Integer indexEquals = spec.indexOf('=');
if (indexEquals >= 1) {
shortName = spec.substring(0, indexEquals);
longName = spec.substring(indexEquals + 1);
} else {
// set them both the same, the trailing @altitude has already been discarded
shortName = longName = spec;
}
if (longName.startsWith("+")) {
longName = longName.substring(1);
}
if (shortName.startsWith("+")) {
shortName = shortName.substring(1);
}
/* try to parse a floor number out of names */
Integer floorNumber = null;
try {
floorNumber = Integer.parseInt(longName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
longName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
try {
// short name takes precedence over long name for floor numbering
floorNumber = Integer.parseInt(shortName);
if (incrementNonNegative) {
if (source == Source.LEVEL_MAP) {
if (floorNumber >= 1)
floorNumber -= 1; // level maps are localized, floor numbers are 0-based
} else {
if (floorNumber >= 0)
shortName = Integer.toString(floorNumber + 1); // level and layer tags are 0-based
}
}
} catch (NumberFormatException e) {}
/* fall back on altitude when necessary */
if (floorNumber == null && altitude != null) {
floorNumber = (int)(altitude / METERS_PER_FLOOR);
_log.warn("Could not determine floor number for layer {}. Guessed {} (0-based) from altitude.", spec, floorNumber);
reliable = false;
}
/* set default value if parsing failed */
if (altitude == null) {
altitude = 0.0;
}
/* signal failure to extract any useful level information */
if (floorNumber == null) {
floorNumber = 0;
_log.warn("Could not determine floor number for layer {}, assumed to be ground-level.",
spec, floorNumber);
reliable = false;
}
return new OSMLevel(floorNumber, altitude, shortName, longName, source, reliable);
}
|
diff --git a/src/gamesincommon/GamesInCommon.java b/src/gamesincommon/GamesInCommon.java
index 7df8894..f887411 100644
--- a/src/gamesincommon/GamesInCommon.java
+++ b/src/gamesincommon/GamesInCommon.java
@@ -1,299 +1,294 @@
package gamesincommon;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
import com.github.koraktor.steamcondenser.steam.community.SteamGame;
import com.github.koraktor.steamcondenser.steam.community.SteamId;
public class GamesInCommon {
Connection connection = null;
private Logger logger;
public GamesInCommon() {
// initialise logger
logger = Logger.getLogger(GamesInCommon.class.getName());
logger.setLevel(Level.ALL);
// initialise database connector
connection = InitialDBCheck();
if (connection == null) {
throw new RuntimeException("Connection could not be establised to local database.");
}
}
public Logger getLogger() {
return logger;
}
/**
* Creates local database, if necessary, and creates tables for all enum entries.
*
* @return A Connection object to the database.
*/
private Connection InitialDBCheck() {
// newDB is TRUE if the database is about to be created by DriverManager.getConnection();
File dbFile = new File("gamedata.db");
boolean newDB = (!(dbFile).exists());
Connection result = null;
try {
Class.forName("org.sqlite.JDBC");
// attempt to connect to the database
result = DriverManager.getConnection("jdbc:sqlite:gamedata.db");
// check all tables from the information schema
Statement statement = result.createStatement();
ResultSet resultSet = null;
// and copy resultset to List object to enable random access
List<String> tableList = new ArrayList<String>();
// skip if new database, as it'll all be new anyway
if (!newDB) {
// query db
resultSet = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
// copy to tableList
while (resultSet.next()) {
tableList.add(resultSet.getString("name"));
}
} else {
logger.log(Level.INFO, "New database created.");
}
// check all filtertypes have a corresponding table, create if one if not present
// skip check and create if the database is new
for (FilterType filter : FilterType.values()) {
boolean filterFound = false;
if (!newDB) {
for (String tableName : tableList) {
if (tableName.equals(filter.getValue())) {
filterFound = true;
}
}
}
// if the tableList is traversed and the filter was not found, create a table for it
if (!filterFound) {
statement.executeUpdate("CREATE TABLE [" + filter.getValue() + "] ( AppID VARCHAR( 16 ) PRIMARY KEY ON CONFLICT FAIL,"
+ "Name VARCHAR( 64 )," + "HasProperty BOOLEAN NOT NULL ON CONFLICT FAIL );");
}
}
} catch (ClassNotFoundException | SQLException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
return result;
}
/**
* Finds common games between an arbitrarily long list of users
*
* @param users
* A list of names to find common games for.
* @return A collection of games common to all users
*/
public Collection<SteamGame> findCommonGames(List<SteamId> users) {
List<Collection<SteamGame>> userGames = new ArrayList<Collection<SteamGame>>();
for (SteamId name : users) {
try {
userGames.add(getGames(name));
logger.log(Level.INFO, "Added user " + name.getNickname() + " (" + name.getSteamId64() + ").");
} catch (SteamCondenserException e) {
logger.log(Level.SEVERE, e.getMessage());
return null;
}
}
Collection<SteamGame> commonGames = mergeSets(userGames);
logger.log(Level.INFO, "Search complete.");
return commonGames;
}
public SteamId checkSteamId(String nameToCheck) throws SteamCondenserException {
try {
return SteamId.create(nameToCheck);
} catch (SteamCondenserException e1) {
try {
return SteamId.create(Long.parseLong(nameToCheck));
} catch (SteamCondenserException | NumberFormatException e2) {
throw e1;
}
}
}
/**
* Finds all games from the given steam user.
*
* @param sId
* The SteamId of the user to get games from.
* @return A set of all games for the give user.
* @throws SteamCondenserException
*/
public Collection<SteamGame> getGames(SteamId sId) throws SteamCondenserException {
return sId.getGames().values();
}
/**
* Returns games that match one or more of the given filter types
*
* @param gameList
* Collection of games to be filtered.
* @param filterList
* Collection of filters to apply.
* @return A collection of games matching one or more of filters.
*/
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
ResultSet tableSet = null;
Statement s = null;
- try {
- s = connection.createStatement();
- tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
- } catch (SQLException e1) {
- logger.log(Level.SEVERE, e1.getMessage(), e1);
- }
for (SteamGame game : gameList) {
// first run a query through the local db
+ try {
+ s = connection.createStatement();
+ tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
+ } catch (SQLException e1) {
+ logger.log(Level.SEVERE, e1.getMessage(), e1);
+ }
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
ResultSet rSet = null;
for (FilterType filter : filterList) {
// default to "needs checking"
filtersToCheck.put(filter, true);
// if the game is not already in the result Collection
if (!result.contains(game)) {
- // WARNING - This does NOT trigger web update if one or more filters are TRUE even if some filters have no DB
- // data
if (filter.getValue().equals((tableSet.getString("name")))) {
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
while ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
}
}
}
- rSet.close();
+ if (rSet != null) {
+ rSet.close();
+ }
}
} catch (SQLException e2) {
logger.log(Level.SEVERE, e2.getMessage());
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
- // success - add to db
- // connection.createStatement().executeUpdate(
- // "INSERT INTO [" + filter.getValue() + "] (AppID, Name, HasProperty) VALUES ('"
- // + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 1)");
- // foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
/**
* Merges multiple user game sets together to keep all games that are the same.
*
* @param userGames
* A list of user game sets.
* @return A set containing all common games.
*/
public Collection<SteamGame> mergeSets(List<Collection<SteamGame>> userGames) {
if (userGames.size() == 0) {
return null;
}
Collection<SteamGame> result = new ArrayList<SteamGame>();
int size = 0;
int index = 0;
for (int i = 0; i < userGames.size(); i++) {
if (userGames.get(i).size() > size) {
size = userGames.get(i).size();
index = i;
}
}
result.addAll(userGames.get(index));
for (int i = 0; i < userGames.size(); i++) {
result.retainAll(userGames.get(i));
}
return result;
}
public String sanitiseInputString(String input) {
return input.replace("'", "''");
}
}
| false | true | public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
ResultSet tableSet = null;
Statement s = null;
try {
s = connection.createStatement();
tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
} catch (SQLException e1) {
logger.log(Level.SEVERE, e1.getMessage(), e1);
}
for (SteamGame game : gameList) {
// first run a query through the local db
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
ResultSet rSet = null;
for (FilterType filter : filterList) {
// default to "needs checking"
filtersToCheck.put(filter, true);
// if the game is not already in the result Collection
if (!result.contains(game)) {
// WARNING - This does NOT trigger web update if one or more filters are TRUE even if some filters have no DB
// data
if (filter.getValue().equals((tableSet.getString("name")))) {
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
while ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
}
}
}
rSet.close();
}
} catch (SQLException e2) {
logger.log(Level.SEVERE, e2.getMessage());
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
// success - add to db
// connection.createStatement().executeUpdate(
// "INSERT INTO [" + filter.getValue() + "] (AppID, Name, HasProperty) VALUES ('"
// + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 1)");
// foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
| public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
ResultSet tableSet = null;
Statement s = null;
for (SteamGame game : gameList) {
// first run a query through the local db
try {
s = connection.createStatement();
tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
} catch (SQLException e1) {
logger.log(Level.SEVERE, e1.getMessage(), e1);
}
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
ResultSet rSet = null;
for (FilterType filter : filterList) {
// default to "needs checking"
filtersToCheck.put(filter, true);
// if the game is not already in the result Collection
if (!result.contains(game)) {
if (filter.getValue().equals((tableSet.getString("name")))) {
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
while ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
}
}
}
if (rSet != null) {
rSet.close();
}
}
} catch (SQLException e2) {
logger.log(Level.SEVERE, e2.getMessage());
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
|
diff --git a/cxx-squid/src/main/java/org/sonar/cxx/parser/CxxGrammarImpl.java b/cxx-squid/src/main/java/org/sonar/cxx/parser/CxxGrammarImpl.java
index fd3cd1b2..64278327 100644
--- a/cxx-squid/src/main/java/org/sonar/cxx/parser/CxxGrammarImpl.java
+++ b/cxx-squid/src/main/java/org/sonar/cxx/parser/CxxGrammarImpl.java
@@ -1,1057 +1,1057 @@
/*
* Sonar C++ Plugin (Community)
* Copyright (C) 2011 Waleri Enns and CONTACT Software GmbH
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.cxx.parser;
import com.sonar.sslr.impl.matcher.GrammarFunctions;
import org.sonar.cxx.api.CxxGrammar;
import org.sonar.cxx.api.CxxKeyword;
import static com.sonar.sslr.api.GenericTokenType.EOF;
import static com.sonar.sslr.api.GenericTokenType.IDENTIFIER;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Predicate.next;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Predicate.not;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.and;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.o2n;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.one2n;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.opt;
import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.or;
import static org.sonar.cxx.api.CxxTokenType.CHARACTER;
import static org.sonar.cxx.api.CxxTokenType.NUMBER;
import static org.sonar.cxx.api.CxxTokenType.STRING;
/**
* Based on the C++ Standard, Appendix A
*/
public class CxxGrammarImpl extends CxxGrammar {
public CxxGrammarImpl() {
toplevel();
expressions();
statements();
declarations();
declarators();
classes();
derivedClasses();
specialMemberFunctions();
overloading();
templates();
exceptionHandling();
misc();
test.is("debugging asset");
GrammarFunctions.enableMemoizationOfMatchesForAllRules(this);
}
private void misc() {
// C++ Standard, Section 2.14.6 "Boolean literals"
bool.is(
or(
CxxKeyword.TRUE,
CxxKeyword.FALSE
)
);
literal.is(
or(
CHARACTER,
STRING,
NUMBER,
bool
)
);
}
private void toplevel() {
translationUnit.is(o2n(declaration), EOF);
}
private void expressions() {
primaryExpression.is(
or(
literal,
CxxKeyword.THIS,
and("(", expression, ")"),
idExpression,
lambdaExpression
)
).skipIfOneChild();
idExpression.is(
or(
qualifiedId,
unqualifiedId
)
);
unqualifiedId.is(
or(
templateId,
operatorFunctionId,
conversionFunctionId,
literalOperatorId,
and("~", className),
and("~", decltypeSpecifier),
IDENTIFIER
)
);
qualifiedId.is(
or(
and(nestedNameSpecifier, opt(CxxKeyword.TEMPLATE), unqualifiedId),
and("::", IDENTIFIER),
and("::", operatorFunctionId),
and("::", literalOperatorId),
and("::", templateId)
)
);
nestedNameSpecifier.is(
or(
and(opt("::"), typeName, "::"),
and(opt("::"), namespaceName, "::"),
and(decltypeSpecifier, "::")
),
o2n(
or(
and(IDENTIFIER, "::"),
and(opt(CxxKeyword.TEMPLATE), simpleTemplateId, "::")
)
)
);
lambdaExpression.is(lambdaIntroducer, opt(lambdaDeclarator), compoundStatement);
lambdaIntroducer.is("[", opt(lambdaCapture), "]");
lambdaCapture.is(
or(
and(captureDefault, ",", captureList),
captureList,
captureDefault
));
captureDefault.is(
or(
"&",
"="
));
captureList.is(and(capture, opt("...")), o2n(",", and(capture, opt("..."))));
capture.is(
or(
IDENTIFIER,
and("&", IDENTIFIER),
CxxKeyword.THIS
));
lambdaDeclarator.is(
"(", parameterDeclarationClause, ")", opt(CxxKeyword.MUTABLE),
opt(exceptionSpecification), opt(attributeSpecifierSeq), opt(trailingReturnType)
);
postfixExpression.is(
or(
and(simpleTypeSpecifier, "(", opt(expressionList), ")"),
and(simpleTypeSpecifier, bracedInitList),
and(typenameSpecifier, "(", opt(expressionList), ")"),
and(typenameSpecifier, bracedInitList),
primaryExpression,
and(CxxKeyword.DYNAMIC_CAST, "<", typeId, ">", "(", expression, ")"),
and(CxxKeyword.STATIC_CAST, "<", typeId, ">", "(", expression, ")"),
and(CxxKeyword.REINTERPRET_CAST, "<", typeId, ">", "(", expression, ")"),
and(CxxKeyword.CONST_CAST, "<", typeId, ">", "(", expression, ")"),
and(CxxKeyword.TYPEID, "(", expression, ")"),
and(CxxKeyword.TYPEID, "(", typeId, ")")
),
// postfixExpression [ expression ]
// postfixExpression [ bracedInitList ]
// postfixExpression ( expressionListopt )
// postfixExpression . templateopt idExpression
// postfixExpression -> templateopt idExpression
// postfixExpression . pseudoDestructorName
// postfixExpression -> pseudoDestructorName
// postfixExpression ++
// postfixExpression --
// should replace the left recursive stuff above
o2n(
or(
and("[", expression, "]"),
and("(", opt(expressionList), ")"),
and(or(".", "->"),
or(and(opt(CxxKeyword.TEMPLATE), idExpression),
pseudoDestructorName)),
"++",
"--"
)
)
).skipIfOneChild();
expressionList.is(initializerList);
pseudoDestructorName.is(
or(
and(opt(nestedNameSpecifier), typeName, "::", "~", typeName),
and(nestedNameSpecifier, CxxKeyword.TEMPLATE, simpleTemplateId, "::", "~", typeName),
and(opt(nestedNameSpecifier), "~", typeName),
and("~", decltypeSpecifier)
)
);
unaryExpression.is(
or(
and(unaryOperator, castExpression),
postfixExpression,
and("++", castExpression),
and("--", castExpression),
and(CxxKeyword.SIZEOF, unaryExpression),
and(CxxKeyword.SIZEOF, "(", typeId, ")"),
and(CxxKeyword.SIZEOF, "...", "(", IDENTIFIER, ")"),
and(CxxKeyword.ALIGNOF, "(", typeId, ")"),
noexceptExpression,
newExpression,
deleteExpression
)
).skipIfOneChild();
unaryOperator.is(
or("*", "&", "+", "-", "!", "~")
);
newExpression.is(
or(
and(opt("::"), CxxKeyword.NEW, opt(newPlacement), newTypeId, opt(newInitializer)),
and(opt("::"), CxxKeyword.NEW, newPlacement, "(", typeId, ")", opt(newInitializer)),
and(opt("::"), CxxKeyword.NEW, "(", typeId, ")", opt(newInitializer))
)
);
newPlacement.is("(", expressionList, ")");
newTypeId.is(typeSpecifierSeq, opt(newDeclarator));
newDeclarator.is(
or(
noptrNewDeclarator,
and(ptrOperator, opt(newDeclarator))
)
);
noptrNewDeclarator.is("[", expression, "]", opt(attributeSpecifierSeq), o2n("[", constantExpression, "]", opt(attributeSpecifierSeq)));
newInitializer.is(
or(
and("(", opt(expressionList), ")"),
bracedInitList
)
);
deleteExpression.is(opt("::"), CxxKeyword.DELETE, opt("[", "]"), castExpression);
noexceptExpression.is(CxxKeyword.NOEXCEPT, "(", expression, ")");
castExpression.is(
or(
and(next("(", typeId, ")"), "(", typeId, ")", castExpression),
unaryExpression
)
).skipIfOneChild();
pmExpression.is(castExpression, o2n(or(".*", "->*"), castExpression)).skipIfOneChild();
multiplicativeExpression.is(pmExpression, o2n(or("*", "/", "%"), pmExpression)).skipIfOneChild();
additiveExpression.is(multiplicativeExpression, o2n(or("+", "-"), multiplicativeExpression)).skipIfOneChild();
shiftExpression.is(additiveExpression, o2n(or("<<", ">>"), additiveExpression)).skipIfOneChild();
relationalExpression.is(shiftExpression, o2n(or("<", ">", "<=", ">="), shiftExpression)).skipIfOneChild();
equalityExpression.is(relationalExpression, o2n(or("==", "!="), relationalExpression)).skipIfOneChild();
andExpression.is(equalityExpression, o2n("&", equalityExpression)).skipIfOneChild();
exclusiveOrExpression.is(andExpression, o2n("^", andExpression)).skipIfOneChild();
inclusiveOrExpression.is(exclusiveOrExpression, o2n("|", exclusiveOrExpression)).skipIfOneChild();
logicalAndExpression.is(inclusiveOrExpression, o2n("&&", inclusiveOrExpression)).skipIfOneChild();
logicalOrExpression.is(logicalAndExpression, o2n("||", logicalAndExpression)).skipIfOneChild();
conditionalExpression.is(
or(
and(logicalOrExpression, "?", expression, ":", assignmentExpression),
logicalOrExpression
)
).skipIfOneChild();
assignmentExpression.is(
or(
and(logicalOrExpression, assignmentOperator, initializerClause),
conditionalExpression,
throwExpression
)
).skipIfOneChild();
assignmentOperator.is(or("=", "*=", "/=", "%=", "+=", "-=", ">>=", "<<=", "&=", "^=", "|="));
expression.is(assignmentExpression, o2n(",", assignmentExpression));
constantExpression.is(conditionalExpression);
}
private void statements() {
statement.is(
or(
labeledStatement,
and(opt(attributeSpecifierSeq), expressionStatement),
and(opt(attributeSpecifierSeq), compoundStatement),
and(opt(attributeSpecifierSeq), selectionStatement),
and(opt(attributeSpecifierSeq), iterationStatement),
and(opt(attributeSpecifierSeq), jumpStatement),
declarationStatement,
and(opt(attributeSpecifierSeq), tryBlock)
)
);
labeledStatement.is(opt(attributeSpecifierSeq), or(IDENTIFIER, and(CxxKeyword.CASE, constantExpression), CxxKeyword.DEFAULT), ":", statement);
expressionStatement.is(opt(expression), ";");
compoundStatement.is("{", opt(statementSeq), "}");
statementSeq.is(one2n(statement));
selectionStatement.is(
or(
and(CxxKeyword.IF, "(", condition, ")", statement, opt(CxxKeyword.ELSE, statement)),
and(CxxKeyword.SWITCH, "(", condition, ")", statement)
)
);
condition.is(
or(
and(opt(attributeSpecifierSeq), conditionDeclSpecifierSeq, declarator, or(and("=", initializerClause), bracedInitList)),
expression
)
);
conditionDeclSpecifierSeq.is(
one2n(
not(and(declarator, or("=", "{"))),
declSpecifier
),
opt(attributeSpecifierSeq)
);
iterationStatement.is(
or(
and(CxxKeyword.WHILE, "(", condition, ")", statement),
and(CxxKeyword.DO, statement, CxxKeyword.WHILE, "(", expression, ")", ";"),
and(CxxKeyword.FOR, "(", forInitStatement, opt(condition), ";", opt(expression), ")", statement),
and(CxxKeyword.FOR, "(", forRangeDeclaration, ":", forRangeInitializer, ")", statement)
)
);
forInitStatement.is(
or(
expressionStatement,
simpleDeclaration
)
);
forRangeDeclaration.is(opt(attributeSpecifierSeq), forrangeDeclSpecifierSeq, declarator);
forrangeDeclSpecifierSeq.is(
one2n(
not(declarator),
declSpecifier
),
opt(attributeSpecifierSeq)
);
forRangeInitializer.is(
or(
expression,
bracedInitList
)
);
jumpStatement.is(
or(
and(CxxKeyword.BREAK, ";"),
and(CxxKeyword.CONTINUE, ";"),
and(CxxKeyword.RETURN, opt(expression), ";"),
and(CxxKeyword.RETURN, bracedInitList, ";"),
and(CxxKeyword.GOTO, IDENTIFIER, ";")
)
);
declarationStatement.is(blockDeclaration);
}
private void declarations() {
declarationSeq.is(one2n(declaration));
declaration.is(
or(
functionDefinition,
blockDeclaration,
templateDeclaration,
explicitInstantiation,
explicitSpecialization,
linkageSpecification,
namespaceDefinition,
emptyDeclaration,
attributeDeclaration
)
);
blockDeclaration.is(
or(
simpleDeclaration,
asmDefinition,
namespaceAliasDefinition,
usingDeclaration,
usingDirective,
staticAssertDeclaration,
aliasDeclaration,
opaqueEnumDeclaration
)
);
aliasDeclaration.is(CxxKeyword.USING, IDENTIFIER, opt(attributeSpecifierSeq), "=", typeId);
simpleDeclaration.is(
or(
and(opt(simpleDeclSpecifierSeq), opt(initDeclaratorList), ";"),
and(attributeSpecifierSeq, opt(simpleDeclSpecifierSeq), initDeclaratorList, ";")
)
);
simpleDeclSpecifierSeq.is(
one2n(
not(and(opt(initDeclaratorList), ";")),
declSpecifier
),
opt(attributeSpecifierSeq)
);
staticAssertDeclaration.is(CxxKeyword.STATIC_ASSERT, "(", constantExpression, ",", STRING, ")", ";");
emptyDeclaration.is(";");
attributeDeclaration.is(attributeSpecifierSeq, ";");
declSpecifier.is(
or(
CxxKeyword.FRIEND, CxxKeyword.TYPEDEF, CxxKeyword.CONSTEXPR,
storageClassSpecifier,
functionSpecifier,
typeSpecifier
)
);
storageClassSpecifier.is(
or(CxxKeyword.REGISTER, CxxKeyword.STATIC, CxxKeyword.THREAD_LOCAL, CxxKeyword.EXTERN, CxxKeyword.MUTABLE)
);
functionSpecifier.is(
or(CxxKeyword.INLINE, CxxKeyword.VIRTUAL, CxxKeyword.EXPLICIT)
);
typedefName.is(IDENTIFIER);
typeSpecifier.is(
or(
classSpecifier,
enumSpecifier,
trailingTypeSpecifier
)
);
trailingTypeSpecifier.is(
or(
simpleTypeSpecifier,
elaboratedTypeSpecifier,
typenameSpecifier,
cvQualifier)
);
typeSpecifierSeq.is(one2n(typeSpecifier), opt(attributeSpecifierSeq));
trailingTypeSpecifierSeq.is(one2n(trailingTypeSpecifier), opt(attributeSpecifierSeq));
simpleTypeSpecifier.is(
or(
"char", "char16_t", "char32_t", "wchar_t", "bool", "short", "int", "long", "signed", "unsigned", "float", "double", "void", "auto",
decltypeSpecifier,
and(nestedNameSpecifier, CxxKeyword.TEMPLATE, simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "void foo(::A a);". Figure out if there is another way
and(opt(or(nestedNameSpecifier, "::")), typeName)
)
);
typeName.is(
or(
simpleTemplateId,
className,
enumName,
typedefName)
);
decltypeSpecifier.is(CxxKeyword.DECLTYPE, "(", expression, ")");
elaboratedTypeSpecifier.is(
or(
and(classKey, opt(nestedNameSpecifier), opt(CxxKeyword.TEMPLATE), simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "friend class ::A". Figure out if there is another way
and(classKey, opt(attributeSpecifierSeq), opt(or(nestedNameSpecifier, "::")), IDENTIFIER),
and(CxxKeyword.ENUM, opt(nestedNameSpecifier), IDENTIFIER)
)
);
enumName.is(IDENTIFIER);
enumSpecifier.is(
or(
and(enumHead, "{", opt(enumeratorList), "}"),
and(enumHead, "{", enumeratorList, ",", "}")
)
);
enumHead.is(enumKey, opt(attributeSpecifierSeq), or(and(nestedNameSpecifier, IDENTIFIER), opt(IDENTIFIER)), opt(enumBase));
opaqueEnumDeclaration.is(enumKey, opt(attributeSpecifierSeq), IDENTIFIER, opt(enumBase), ";");
- enumKey.is(CxxKeyword.ENUM, opt(CxxKeyword.CLASS, CxxKeyword.STRUCT));
+ enumKey.is(CxxKeyword.ENUM, opt(or(CxxKeyword.CLASS, CxxKeyword.STRUCT)));
enumBase.is(":", typeSpecifierSeq);
enumeratorList.is(enumeratorDefinition, o2n(",", enumeratorDefinition));
enumeratorDefinition.is(enumerator, opt("=", constantExpression));
enumerator.is(IDENTIFIER);
namespaceName.is(
or(
originalNamespaceName,
namespaceAlias
)
);
originalNamespaceName.is(IDENTIFIER);
namespaceDefinition.is(
or(
namedNamespaceDefinition,
unnamedNamespaceDefinition
)
);
namedNamespaceDefinition.is(
or(
originalNamespaceDefinition,
extensionNamespaceDefinition
)
);
originalNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, IDENTIFIER, "{", namespaceBody, "}");
extensionNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, originalNamespaceName, "{", namespaceBody, "}");
unnamedNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, "{", namespaceBody, "}");
namespaceBody.is(opt(declarationSeq));
namespaceAlias.is(IDENTIFIER);
namespaceAliasDefinition.is(CxxKeyword.NAMESPACE, IDENTIFIER, "=", qualifiedNamespaceSpecifier, ";");
qualifiedNamespaceSpecifier.is(opt(nestedNameSpecifier), namespaceName);
usingDeclaration.is(
or(
and(CxxKeyword.USING, opt(CxxKeyword.TYPENAME), nestedNameSpecifier, unqualifiedId, ";"),
and(CxxKeyword.USING, "::", unqualifiedId, ";")
)
);
usingDirective.is(opt(attributeSpecifier), CxxKeyword.USING, CxxKeyword.NAMESPACE, opt("::"), opt(nestedNameSpecifier), namespaceName, ";");
asmDefinition.is(CxxKeyword.ASM, "(", STRING, ")", ";");
linkageSpecification.is(CxxKeyword.EXTERN, STRING, or(and("{", opt(declarationSeq), "}"), declaration));
attributeSpecifierSeq.is(one2n(attributeSpecifier));
attributeSpecifier.is(
or(
and("[", "[", attributeList, "]", "]"),
alignmentSpecifier
));
alignmentSpecifier.is(
or(
and(CxxKeyword.ALIGNAS, "(", typeId, opt("..."), ")"),
and(CxxKeyword.ALIGNAS, "(", assignmentExpression, opt("..."), ")")
));
attributeList.is(
or(
and(attribute, "...", o2n(",", attribute, "...")),
and(opt(attribute), o2n(",", opt(attribute)))
));
attribute.is(attributeToken, opt(attributeArgumentClause));
attributeToken.is(
or(
attributeScopedToken,
IDENTIFIER
));
attributeScopedToken.is(attributeNamespace, "::", IDENTIFIER);
attributeNamespace.is(IDENTIFIER);
attributeArgumentClause.is("(", balancedTokenSeq, ")");
balancedTokenSeq.is(o2n(balancedToken));
balancedToken.is(
or(
IDENTIFIER,
and("(", balancedTokenSeq, ")"),
and("{", balancedTokenSeq, "}"),
and("[", balancedTokenSeq, "]")
));
}
private void declarators() {
initDeclaratorList.is(initDeclarator, o2n(",", initDeclarator));
initDeclarator.is(declarator, opt(initializer));
declarator.is(
or(
ptrDeclarator,
and(noptrDeclarator, parametersAndQualifiers, trailingReturnType)
)
);
ptrDeclarator.is(
or(
and(ptrOperator, ptrDeclarator),
noptrDeclarator
)
);
noptrDeclarator.is(
or(
and(declaratorId, opt(attributeSpecifierSeq)),
and("(", ptrDeclarator, ")")
),
o2n(
or(
parametersAndQualifiers,
and("[", opt(constantExpression), "]", opt(attributeSpecifierSeq))
)
)
);
parametersAndQualifiers.is("(", parameterDeclarationClause, ")", opt(attributeSpecifierSeq), opt(cvQualifierSeq), opt(refQualifier), opt(exceptionSpecification));
trailingReturnType.is("->", trailingTypeSpecifierSeq, opt(abstractDeclarator));
ptrOperator.is(
or(
and("*", opt(attributeSpecifierSeq), opt(cvQualifierSeq)),
and("&", opt(attributeSpecifierSeq)),
and("&&", opt(attributeSpecifierSeq)),
and(nestedNameSpecifier, "*", opt(attributeSpecifierSeq), opt(cvQualifierSeq))
)
);
cvQualifierSeq.is(one2n(cvQualifier));
cvQualifier.is(
or(CxxKeyword.CONST, CxxKeyword.VOLATILE)
);
refQualifier.is(
or("&", "&&")
);
declaratorId.is(
or(
and(opt(nestedNameSpecifier), className),
and(opt("..."), idExpression)
)
);
typeId.is(typeSpecifierSeq, opt(abstractDeclarator));
abstractDeclarator.is(
or(
ptrAbstractDeclarator,
and(opt(noptrAbstractDeclarator), parametersAndQualifiers, trailingReturnType),
abstractPackDeclarator
)
);
ptrAbstractDeclarator.is(o2n(ptrOperator), opt(noptrAbstractDeclarator));
noptrAbstractDeclarator.is(
opt("(", ptrAbstractDeclarator, ")"),
o2n(
or(
parametersAndQualifiers,
and("[", opt(constantExpression), "]", opt(attributeSpecifierSeq))
)
)
);
abstractPackDeclarator.is(o2n(ptrOperator), noptrAbstractPackDeclarator);
noptrAbstractPackDeclarator.is(
"...",
o2n(or(parametersAndQualifiers,
and("[", opt(constantExpression), "]", opt(attributeSpecifierSeq))
)
)
);
parameterDeclarationClause.is(
or(
and(parameterDeclarationList, ",", "..."),
and(opt(parameterDeclarationList), opt("...")),
"..."
)
);
parameterDeclarationList.is(parameterDeclaration, o2n(",", parameterDeclaration));
parameterDeclaration.is(
or(
and(opt(attributeSpecifierSeq), parameterDeclSpecifierSeq, declarator, opt("=", initializerClause)),
and(opt(attributeSpecifierSeq), parameterDeclSpecifierSeq, opt(abstractDeclarator), opt("=", initializerClause))
)
);
parameterDeclSpecifierSeq.is(
o2n(
not(and(opt(declarator), or("=", ")", ","))),
declSpecifier
),
opt(attributeSpecifierSeq)
);
functionDefinition.is(opt(attributeSpecifierSeq), opt(functionDeclSpecifierSeq), declarator, opt(virtSpecifierSeq), functionBody);
functionDeclSpecifierSeq.is(
one2n(
not(and(declarator, opt(virtSpecifierSeq), functionBody)),
declSpecifier
),
opt(attributeSpecifierSeq)
);
functionBody.is(
or(
and(opt(ctorInitializer), compoundStatement),
functionTryBlock,
and("=", CxxKeyword.DELETE, ";"),
and("=", CxxKeyword.DEFAULT, ";")
)
);
initializer.is(
or(
and("(", expressionList, ")"),
braceOrEqualInitializer
)
);
braceOrEqualInitializer.is(
or(
and("=", initializerClause),
bracedInitList
)
);
initializerClause.is(
or(
assignmentExpression,
bracedInitList
)
);
initializerList.is(initializerClause, opt("..."), o2n(",", initializerClause, opt("...")));
bracedInitList.is("{", opt(initializerList), opt(","), "}");
}
private void classes() {
className.is(
or(
simpleTemplateId,
IDENTIFIER
)
);
classSpecifier.is(classHead, "{", opt(memberSpecification), "}");
classHead.is(
or(
and(classKey, opt(attributeSpecifierSeq), classHeadName, opt(classVirtSpecifier), opt(baseClause)),
and(classKey, opt(attributeSpecifierSeq), opt(baseClause))
)
);
classHeadName.is(opt(nestedNameSpecifier), className);
classVirtSpecifier.is(CxxKeyword.FINAL);
classKey.is(
or(CxxKeyword.CLASS, CxxKeyword.STRUCT, CxxKeyword.UNION)
);
memberSpecification.is(
one2n(
or(
memberDeclaration,
and(accessSpecifier, ":")
)
)
);
memberDeclaration.is(
or(
and(opt(attributeSpecifierSeq), opt(memberDeclSpecifierSeq), opt(memberDeclaratorList), ";"),
and(functionDefinition, opt(";")),
and(opt("::"), nestedNameSpecifier, opt(CxxKeyword.TEMPLATE), unqualifiedId, ";"),
usingDeclaration,
staticAssertDeclaration,
templateDeclaration,
aliasDeclaration
)
);
memberDeclSpecifierSeq.is(
one2n(
not(and(opt(memberDeclaratorList), ";")),
declSpecifier
),
opt(attributeSpecifierSeq)
);
memberDeclaratorList.is(memberDeclarator, o2n(",", memberDeclarator));
memberDeclarator.is(
or(
and(declarator, braceOrEqualInitializer),
and(declarator, virtSpecifierSeq, opt(pureSpecifier)),
and(opt(IDENTIFIER), opt(attributeSpecifierSeq), ":", constantExpression),
declarator
)
);
virtSpecifierSeq.is(one2n(virtSpecifier));
virtSpecifier.is(
or(CxxKeyword.OVERRIDE, CxxKeyword.FINAL)
);
pureSpecifier.is("=", "0");
}
private void derivedClasses() {
baseClause.is(":", baseSpecifierList);
baseSpecifierList.is(baseSpecifier, opt("..."), o2n(",", baseSpecifier, opt("...")));
baseSpecifier.is(
or(
and(opt(attributeSpecifierSeq), baseTypeSpecifier),
and(opt(attributeSpecifierSeq), CxxKeyword.VIRTUAL, opt(accessSpecifier), baseTypeSpecifier),
and(opt(attributeSpecifierSeq), accessSpecifier, opt(CxxKeyword.VIRTUAL), baseTypeSpecifier)
)
);
classOrDecltype.is(
or(
and(opt(nestedNameSpecifier), className),
decltypeSpecifier)
);
baseTypeSpecifier.is(classOrDecltype);
accessSpecifier.is(
or(CxxKeyword.PRIVATE, CxxKeyword.PROTECTED, CxxKeyword.PUBLIC)
);
}
private void specialMemberFunctions() {
conversionFunctionId.is(CxxKeyword.OPERATOR, conversionTypeId);
conversionTypeId.is(typeSpecifierSeq, opt(conversionDeclarator));
conversionDeclarator.is(one2n(ptrOperator));
ctorInitializer.is(":", memInitializerList);
memInitializerList.is(memInitializer, opt("..."), o2n(",", memInitializer, opt("...")));
memInitializer.is(memInitializerId, or(and("(", opt(expressionList), ")"), bracedInitList));
memInitializerId.is(
or(
classOrDecltype,
IDENTIFIER
)
);
}
private void overloading() {
operatorFunctionId.is(CxxKeyword.OPERATOR, operator);
operator.is(
or(
and(CxxKeyword.NEW, "[", "]"),
and(CxxKeyword.DELETE, "[", "]"),
CxxKeyword.NEW, CxxKeyword.DELETE,
"+", "-", "!", "=", "^=", "&=", "<=", ">=",
and("(", ")"),
and("[", "]"),
"*", "<", "|=", "&&", "/",
">", "<<", "||", "%", "+=", ">>", "++", "^", "-=", ">>=", "--", "&", "*=", "<<=",
",", "|", "/=", "==", "->*", "~", "%=", "!=", "->"
)
);
literalOperatorId.is(CxxKeyword.OPERATOR, "\"\"", IDENTIFIER);
}
private void templates() {
templateDeclaration.is(CxxKeyword.TEMPLATE, "<", templateParameterList, ">", declaration);
templateParameterList.is(templateParameter, o2n(",", templateParameter));
templateParameter.is(
or(
typeParameter,
parameterDeclaration
)
);
typeParameter.is(
or(
and(CxxKeyword.CLASS, opt(IDENTIFIER), "=", typeId),
and(CxxKeyword.CLASS, opt("..."), opt(IDENTIFIER)),
and(CxxKeyword.TYPENAME, opt(IDENTIFIER), "=", typeId),
and(CxxKeyword.TYPENAME, opt("..."), opt(IDENTIFIER)),
and(CxxKeyword.TEMPLATE, "<", templateParameterList, ">", CxxKeyword.CLASS, opt(IDENTIFIER), "=", idExpression),
and(CxxKeyword.TEMPLATE, "<", templateParameterList, ">", CxxKeyword.CLASS, opt("..."), opt(IDENTIFIER))
)
);
simpleTemplateId.is(templateName, "<", opt(templateArgumentList), ">");
templateId.is(
or(
simpleTemplateId,
and(operatorFunctionId, "<", opt(templateArgumentList), ">"),
and(literalOperatorId, "<", opt(templateArgumentList), ">")
)
);
templateName.is(IDENTIFIER);
templateArgumentList.is(templateArgument, opt("..."), o2n(",", templateArgument, opt("...")));
templateArgument.is(
or(
typeId,
// FIXME: workaround to parse stuff like "carray<int, 10>"
// actually, it should be covered by the next rule (constantExpression)
// but it doesnt work because of ambiguity template syntax <--> relationalExpression
shiftExpression,
constantExpression,
idExpression
)
);
typenameSpecifier.is(
CxxKeyword.TYPENAME, nestedNameSpecifier,
or(and(opt(CxxKeyword.TEMPLATE), simpleTemplateId), IDENTIFIER));
explicitInstantiation.is(opt(CxxKeyword.EXTERN), CxxKeyword.TEMPLATE, declaration);
explicitSpecialization.is(CxxKeyword.TEMPLATE, "<", ">", declaration);
}
private void exceptionHandling() {
tryBlock.is(CxxKeyword.TRY, compoundStatement, handlerSeq);
functionTryBlock.is(CxxKeyword.TRY, opt(ctorInitializer), compoundStatement, handlerSeq);
handlerSeq.is(one2n(handler));
handler.is(CxxKeyword.CATCH, "(", exceptionDeclaration, ")", compoundStatement);
exceptionDeclaration.is(
or(
and(opt(attributeSpecifierSeq), typeSpecifierSeq, or(declarator, opt(abstractDeclarator))),
"..."
)
);
throwExpression.is(CxxKeyword.THROW, opt(assignmentExpression));
exceptionSpecification.is(
or(
dynamicExceptionSpecification,
noexceptSpecification
)
);
dynamicExceptionSpecification.is(CxxKeyword.THROW, "(", opt(typeIdList), ")");
typeIdList.is(typeId, opt("..."), o2n(",", typeId, opt("...")));
noexceptSpecification.is(CxxKeyword.NOEXCEPT, opt("(", constantExpression, ")"));
}
}
| true | true | private void declarations() {
declarationSeq.is(one2n(declaration));
declaration.is(
or(
functionDefinition,
blockDeclaration,
templateDeclaration,
explicitInstantiation,
explicitSpecialization,
linkageSpecification,
namespaceDefinition,
emptyDeclaration,
attributeDeclaration
)
);
blockDeclaration.is(
or(
simpleDeclaration,
asmDefinition,
namespaceAliasDefinition,
usingDeclaration,
usingDirective,
staticAssertDeclaration,
aliasDeclaration,
opaqueEnumDeclaration
)
);
aliasDeclaration.is(CxxKeyword.USING, IDENTIFIER, opt(attributeSpecifierSeq), "=", typeId);
simpleDeclaration.is(
or(
and(opt(simpleDeclSpecifierSeq), opt(initDeclaratorList), ";"),
and(attributeSpecifierSeq, opt(simpleDeclSpecifierSeq), initDeclaratorList, ";")
)
);
simpleDeclSpecifierSeq.is(
one2n(
not(and(opt(initDeclaratorList), ";")),
declSpecifier
),
opt(attributeSpecifierSeq)
);
staticAssertDeclaration.is(CxxKeyword.STATIC_ASSERT, "(", constantExpression, ",", STRING, ")", ";");
emptyDeclaration.is(";");
attributeDeclaration.is(attributeSpecifierSeq, ";");
declSpecifier.is(
or(
CxxKeyword.FRIEND, CxxKeyword.TYPEDEF, CxxKeyword.CONSTEXPR,
storageClassSpecifier,
functionSpecifier,
typeSpecifier
)
);
storageClassSpecifier.is(
or(CxxKeyword.REGISTER, CxxKeyword.STATIC, CxxKeyword.THREAD_LOCAL, CxxKeyword.EXTERN, CxxKeyword.MUTABLE)
);
functionSpecifier.is(
or(CxxKeyword.INLINE, CxxKeyword.VIRTUAL, CxxKeyword.EXPLICIT)
);
typedefName.is(IDENTIFIER);
typeSpecifier.is(
or(
classSpecifier,
enumSpecifier,
trailingTypeSpecifier
)
);
trailingTypeSpecifier.is(
or(
simpleTypeSpecifier,
elaboratedTypeSpecifier,
typenameSpecifier,
cvQualifier)
);
typeSpecifierSeq.is(one2n(typeSpecifier), opt(attributeSpecifierSeq));
trailingTypeSpecifierSeq.is(one2n(trailingTypeSpecifier), opt(attributeSpecifierSeq));
simpleTypeSpecifier.is(
or(
"char", "char16_t", "char32_t", "wchar_t", "bool", "short", "int", "long", "signed", "unsigned", "float", "double", "void", "auto",
decltypeSpecifier,
and(nestedNameSpecifier, CxxKeyword.TEMPLATE, simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "void foo(::A a);". Figure out if there is another way
and(opt(or(nestedNameSpecifier, "::")), typeName)
)
);
typeName.is(
or(
simpleTemplateId,
className,
enumName,
typedefName)
);
decltypeSpecifier.is(CxxKeyword.DECLTYPE, "(", expression, ")");
elaboratedTypeSpecifier.is(
or(
and(classKey, opt(nestedNameSpecifier), opt(CxxKeyword.TEMPLATE), simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "friend class ::A". Figure out if there is another way
and(classKey, opt(attributeSpecifierSeq), opt(or(nestedNameSpecifier, "::")), IDENTIFIER),
and(CxxKeyword.ENUM, opt(nestedNameSpecifier), IDENTIFIER)
)
);
enumName.is(IDENTIFIER);
enumSpecifier.is(
or(
and(enumHead, "{", opt(enumeratorList), "}"),
and(enumHead, "{", enumeratorList, ",", "}")
)
);
enumHead.is(enumKey, opt(attributeSpecifierSeq), or(and(nestedNameSpecifier, IDENTIFIER), opt(IDENTIFIER)), opt(enumBase));
opaqueEnumDeclaration.is(enumKey, opt(attributeSpecifierSeq), IDENTIFIER, opt(enumBase), ";");
enumKey.is(CxxKeyword.ENUM, opt(CxxKeyword.CLASS, CxxKeyword.STRUCT));
enumBase.is(":", typeSpecifierSeq);
enumeratorList.is(enumeratorDefinition, o2n(",", enumeratorDefinition));
enumeratorDefinition.is(enumerator, opt("=", constantExpression));
enumerator.is(IDENTIFIER);
namespaceName.is(
or(
originalNamespaceName,
namespaceAlias
)
);
originalNamespaceName.is(IDENTIFIER);
namespaceDefinition.is(
or(
namedNamespaceDefinition,
unnamedNamespaceDefinition
)
);
namedNamespaceDefinition.is(
or(
originalNamespaceDefinition,
extensionNamespaceDefinition
)
);
originalNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, IDENTIFIER, "{", namespaceBody, "}");
extensionNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, originalNamespaceName, "{", namespaceBody, "}");
unnamedNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, "{", namespaceBody, "}");
namespaceBody.is(opt(declarationSeq));
namespaceAlias.is(IDENTIFIER);
namespaceAliasDefinition.is(CxxKeyword.NAMESPACE, IDENTIFIER, "=", qualifiedNamespaceSpecifier, ";");
qualifiedNamespaceSpecifier.is(opt(nestedNameSpecifier), namespaceName);
usingDeclaration.is(
or(
and(CxxKeyword.USING, opt(CxxKeyword.TYPENAME), nestedNameSpecifier, unqualifiedId, ";"),
and(CxxKeyword.USING, "::", unqualifiedId, ";")
)
);
usingDirective.is(opt(attributeSpecifier), CxxKeyword.USING, CxxKeyword.NAMESPACE, opt("::"), opt(nestedNameSpecifier), namespaceName, ";");
asmDefinition.is(CxxKeyword.ASM, "(", STRING, ")", ";");
linkageSpecification.is(CxxKeyword.EXTERN, STRING, or(and("{", opt(declarationSeq), "}"), declaration));
attributeSpecifierSeq.is(one2n(attributeSpecifier));
attributeSpecifier.is(
or(
and("[", "[", attributeList, "]", "]"),
alignmentSpecifier
));
alignmentSpecifier.is(
or(
and(CxxKeyword.ALIGNAS, "(", typeId, opt("..."), ")"),
and(CxxKeyword.ALIGNAS, "(", assignmentExpression, opt("..."), ")")
));
attributeList.is(
or(
and(attribute, "...", o2n(",", attribute, "...")),
and(opt(attribute), o2n(",", opt(attribute)))
));
attribute.is(attributeToken, opt(attributeArgumentClause));
attributeToken.is(
or(
attributeScopedToken,
IDENTIFIER
));
attributeScopedToken.is(attributeNamespace, "::", IDENTIFIER);
attributeNamespace.is(IDENTIFIER);
attributeArgumentClause.is("(", balancedTokenSeq, ")");
balancedTokenSeq.is(o2n(balancedToken));
balancedToken.is(
or(
IDENTIFIER,
and("(", balancedTokenSeq, ")"),
and("{", balancedTokenSeq, "}"),
and("[", balancedTokenSeq, "]")
));
}
| private void declarations() {
declarationSeq.is(one2n(declaration));
declaration.is(
or(
functionDefinition,
blockDeclaration,
templateDeclaration,
explicitInstantiation,
explicitSpecialization,
linkageSpecification,
namespaceDefinition,
emptyDeclaration,
attributeDeclaration
)
);
blockDeclaration.is(
or(
simpleDeclaration,
asmDefinition,
namespaceAliasDefinition,
usingDeclaration,
usingDirective,
staticAssertDeclaration,
aliasDeclaration,
opaqueEnumDeclaration
)
);
aliasDeclaration.is(CxxKeyword.USING, IDENTIFIER, opt(attributeSpecifierSeq), "=", typeId);
simpleDeclaration.is(
or(
and(opt(simpleDeclSpecifierSeq), opt(initDeclaratorList), ";"),
and(attributeSpecifierSeq, opt(simpleDeclSpecifierSeq), initDeclaratorList, ";")
)
);
simpleDeclSpecifierSeq.is(
one2n(
not(and(opt(initDeclaratorList), ";")),
declSpecifier
),
opt(attributeSpecifierSeq)
);
staticAssertDeclaration.is(CxxKeyword.STATIC_ASSERT, "(", constantExpression, ",", STRING, ")", ";");
emptyDeclaration.is(";");
attributeDeclaration.is(attributeSpecifierSeq, ";");
declSpecifier.is(
or(
CxxKeyword.FRIEND, CxxKeyword.TYPEDEF, CxxKeyword.CONSTEXPR,
storageClassSpecifier,
functionSpecifier,
typeSpecifier
)
);
storageClassSpecifier.is(
or(CxxKeyword.REGISTER, CxxKeyword.STATIC, CxxKeyword.THREAD_LOCAL, CxxKeyword.EXTERN, CxxKeyword.MUTABLE)
);
functionSpecifier.is(
or(CxxKeyword.INLINE, CxxKeyword.VIRTUAL, CxxKeyword.EXPLICIT)
);
typedefName.is(IDENTIFIER);
typeSpecifier.is(
or(
classSpecifier,
enumSpecifier,
trailingTypeSpecifier
)
);
trailingTypeSpecifier.is(
or(
simpleTypeSpecifier,
elaboratedTypeSpecifier,
typenameSpecifier,
cvQualifier)
);
typeSpecifierSeq.is(one2n(typeSpecifier), opt(attributeSpecifierSeq));
trailingTypeSpecifierSeq.is(one2n(trailingTypeSpecifier), opt(attributeSpecifierSeq));
simpleTypeSpecifier.is(
or(
"char", "char16_t", "char32_t", "wchar_t", "bool", "short", "int", "long", "signed", "unsigned", "float", "double", "void", "auto",
decltypeSpecifier,
and(nestedNameSpecifier, CxxKeyword.TEMPLATE, simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "void foo(::A a);". Figure out if there is another way
and(opt(or(nestedNameSpecifier, "::")), typeName)
)
);
typeName.is(
or(
simpleTemplateId,
className,
enumName,
typedefName)
);
decltypeSpecifier.is(CxxKeyword.DECLTYPE, "(", expression, ")");
elaboratedTypeSpecifier.is(
or(
and(classKey, opt(nestedNameSpecifier), opt(CxxKeyword.TEMPLATE), simpleTemplateId),
// TODO: the "::"-Alternative to nested-name-specifier is because of need to parse
// stuff like "friend class ::A". Figure out if there is another way
and(classKey, opt(attributeSpecifierSeq), opt(or(nestedNameSpecifier, "::")), IDENTIFIER),
and(CxxKeyword.ENUM, opt(nestedNameSpecifier), IDENTIFIER)
)
);
enumName.is(IDENTIFIER);
enumSpecifier.is(
or(
and(enumHead, "{", opt(enumeratorList), "}"),
and(enumHead, "{", enumeratorList, ",", "}")
)
);
enumHead.is(enumKey, opt(attributeSpecifierSeq), or(and(nestedNameSpecifier, IDENTIFIER), opt(IDENTIFIER)), opt(enumBase));
opaqueEnumDeclaration.is(enumKey, opt(attributeSpecifierSeq), IDENTIFIER, opt(enumBase), ";");
enumKey.is(CxxKeyword.ENUM, opt(or(CxxKeyword.CLASS, CxxKeyword.STRUCT)));
enumBase.is(":", typeSpecifierSeq);
enumeratorList.is(enumeratorDefinition, o2n(",", enumeratorDefinition));
enumeratorDefinition.is(enumerator, opt("=", constantExpression));
enumerator.is(IDENTIFIER);
namespaceName.is(
or(
originalNamespaceName,
namespaceAlias
)
);
originalNamespaceName.is(IDENTIFIER);
namespaceDefinition.is(
or(
namedNamespaceDefinition,
unnamedNamespaceDefinition
)
);
namedNamespaceDefinition.is(
or(
originalNamespaceDefinition,
extensionNamespaceDefinition
)
);
originalNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, IDENTIFIER, "{", namespaceBody, "}");
extensionNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, originalNamespaceName, "{", namespaceBody, "}");
unnamedNamespaceDefinition.is(opt(CxxKeyword.INLINE), CxxKeyword.NAMESPACE, "{", namespaceBody, "}");
namespaceBody.is(opt(declarationSeq));
namespaceAlias.is(IDENTIFIER);
namespaceAliasDefinition.is(CxxKeyword.NAMESPACE, IDENTIFIER, "=", qualifiedNamespaceSpecifier, ";");
qualifiedNamespaceSpecifier.is(opt(nestedNameSpecifier), namespaceName);
usingDeclaration.is(
or(
and(CxxKeyword.USING, opt(CxxKeyword.TYPENAME), nestedNameSpecifier, unqualifiedId, ";"),
and(CxxKeyword.USING, "::", unqualifiedId, ";")
)
);
usingDirective.is(opt(attributeSpecifier), CxxKeyword.USING, CxxKeyword.NAMESPACE, opt("::"), opt(nestedNameSpecifier), namespaceName, ";");
asmDefinition.is(CxxKeyword.ASM, "(", STRING, ")", ";");
linkageSpecification.is(CxxKeyword.EXTERN, STRING, or(and("{", opt(declarationSeq), "}"), declaration));
attributeSpecifierSeq.is(one2n(attributeSpecifier));
attributeSpecifier.is(
or(
and("[", "[", attributeList, "]", "]"),
alignmentSpecifier
));
alignmentSpecifier.is(
or(
and(CxxKeyword.ALIGNAS, "(", typeId, opt("..."), ")"),
and(CxxKeyword.ALIGNAS, "(", assignmentExpression, opt("..."), ")")
));
attributeList.is(
or(
and(attribute, "...", o2n(",", attribute, "...")),
and(opt(attribute), o2n(",", opt(attribute)))
));
attribute.is(attributeToken, opt(attributeArgumentClause));
attributeToken.is(
or(
attributeScopedToken,
IDENTIFIER
));
attributeScopedToken.is(attributeNamespace, "::", IDENTIFIER);
attributeNamespace.is(IDENTIFIER);
attributeArgumentClause.is("(", balancedTokenSeq, ")");
balancedTokenSeq.is(o2n(balancedToken));
balancedToken.is(
or(
IDENTIFIER,
and("(", balancedTokenSeq, ")"),
and("{", balancedTokenSeq, "}"),
and("[", balancedTokenSeq, "]")
));
}
|
diff --git a/loci/formats/out/ICSWriter.java b/loci/formats/out/ICSWriter.java
index 617b90f51..2a39e8300 100644
--- a/loci/formats/out/ICSWriter.java
+++ b/loci/formats/out/ICSWriter.java
@@ -1,203 +1,205 @@
//
// ICSWriter.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.out;
import java.awt.Image;
import java.awt.image.*;
import java.io.*;
import java.util.StringTokenizer;
import loci.formats.*;
import loci.formats.meta.MetadataRetrieve;
/**
* ICSWriter is the file format writer for ICS files. It writes ICS version 2
* files only.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/out/ICSWriter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/out/ICSWriter.java">SVN</a></dd></dl>
*/
public class ICSWriter extends FormatWriter {
// -- Fields --
private RandomAccessFile out;
// -- Constructor --
public ICSWriter() { super("Image Cytometry Standard", "ics"); }
// -- IFormatWriter API methods --
/* @see loci.formats.IFormatWriter#saveImage(Image, int, boolean, boolean) */
public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getPixelBytes(img, false);
int bytesPerPixel =
FormatTools.getBytesPerPixel(ImageTools.getPixelType(img));
if (!initialized) {
initialized = true;
out = new RandomAccessFile(currentId, "rw");
out.writeBytes("\t\n");
out.writeBytes("ics_version\t2.0\n");
out.writeBytes("filename\t" + currentId + "\n");
out.writeBytes("layout\tparameters\t6\n");
MetadataRetrieve meta = getMetadataRetrieve();
if (meta == null) {
throw new FormatException("MetadataRetrieve is null. " +
"Call setMetadataRetrieve(MetadataRetrieve) before calling " +
"saveImage(Image, boolean).");
}
String order = meta.getPixelsDimensionOrder(series, 0);
int x = meta.getPixelsSizeX(series, 0).intValue();
int y = meta.getPixelsSizeY(series, 0).intValue();
int z = meta.getPixelsSizeZ(series, 0).intValue();
int c = meta.getPixelsSizeC(series, 0).intValue();
int t = meta.getPixelsSizeT(series, 0).intValue();
int pixelType =
FormatTools.pixelTypeFromString(meta.getPixelsPixelType(series, 0));
StringBuffer dimOrder = new StringBuffer();
int[] sizes = new int[6];
int nextSize = 0;
sizes[nextSize++] = 8 * FormatTools.getBytesPerPixel(pixelType);
if (byteData.length > 1) {
dimOrder.append("ch\t");
sizes[nextSize++] = c;
}
for (int i=0; i<order.length(); i++) {
if (order.charAt(i) == 'C' && byteData.length == 1) {
dimOrder.append("ch");
sizes[nextSize++] = c;
}
else {
if (order.charAt(i) == 'X') sizes[nextSize++] = x;
else if (order.charAt(i) == 'Y') sizes[nextSize++] = y;
else if (order.charAt(i) == 'Z') sizes[nextSize++] = z;
else if (order.charAt(i) == 'T') sizes[nextSize++] = t;
- dimOrder.append(String.valueOf(order.charAt(i)).toLowerCase());
+ if (order.charAt(i) != 'C') {
+ dimOrder.append(String.valueOf(order.charAt(i)).toLowerCase());
+ }
}
dimOrder.append("\t");
}
out.writeBytes("layout\torder\tbits\t" + dimOrder.toString() + "\n");
out.writeBytes("layout\tsizes\t");
for (int i=0; i<sizes.length; i++) {
out.writeBytes(sizes[i] + "\t");
if (i == sizes.length - 1) out.writeBytes("\n");
}
boolean signed = pixelType == FormatTools.INT8 ||
pixelType == FormatTools.INT16 || pixelType == FormatTools.INT32;
out.writeBytes("representation\tformat\t" +
(pixelType == FormatTools.FLOAT ? "real\n" : "integer\n"));
out.writeBytes("representation\tsign\t" +
(signed ? "signed\n" : "unsigned\n"));
out.writeBytes("representation\tcompression\tuncompressed\n");
out.writeBytes("representation\tbyte_order\t");
for (int i=0; i<sizes[0]/8; i++) {
out.writeBytes(((sizes[0] / 8) - i) + "\t");
}
out.writeBytes("\nparameter\tscale\t1.000000\t");
StringTokenizer st = new StringTokenizer(dimOrder.toString(), "\t");
StringBuffer units = new StringBuffer();
while (st.hasMoreTokens()) {
String token = st.nextToken();
Number value = null;
if (token.equals("x")) {
value = meta.getDimensionsPhysicalSizeX(0, 0);
units.append("micrometers\t");
}
else if (token.equals("y")) {
value = meta.getDimensionsPhysicalSizeY(0, 0);
units.append("micrometers\t");
}
else if (token.equals("z")) {
value = meta.getDimensionsPhysicalSizeZ(0, 0);
units.append("micrometers\t");
}
else if (token.equals("t")) {
value = meta.getDimensionsTimeIncrement(0, 0);
units.append("seconds\t");
}
else if (token.equals("ch")) {
value = meta.getDimensionsWaveIncrement(0, 0);
units.append("nm\t");
}
if (value == null) out.writeBytes("1.000000\t");
else out.writeBytes(value + "\t");
}
out.writeBytes("\nparameter\tunits\tbits\t" + units.toString() + "\n");
out.writeBytes("\nend\n");
}
if (byteData.length == 1) out.write(byteData[0]);
else {
for (int pixel=0; pixel<byteData[0].length/bytesPerPixel; pixel++) {
for (int channel=0; channel<byteData.length; channel++) {
out.write(byteData[channel], pixel*bytesPerPixel, bytesPerPixel);
}
}
}
if (last) close();
}
/* @see loci.formats.IFormatWriter#canDoStacks() */
public boolean canDoStacks() { return true; }
/* @see loci.formats.IFormatWriter#getPixelTypes() */
public int[] getPixelTypes() {
return new int[] {FormatTools.INT8, FormatTools.UINT8, FormatTools.INT16,
FormatTools.UINT16, FormatTools.INT32, FormatTools.UINT32,
FormatTools.FLOAT};
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
if (out != null) out.close();
out = null;
currentId = null;
initialized = false;
}
}
| true | true | public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getPixelBytes(img, false);
int bytesPerPixel =
FormatTools.getBytesPerPixel(ImageTools.getPixelType(img));
if (!initialized) {
initialized = true;
out = new RandomAccessFile(currentId, "rw");
out.writeBytes("\t\n");
out.writeBytes("ics_version\t2.0\n");
out.writeBytes("filename\t" + currentId + "\n");
out.writeBytes("layout\tparameters\t6\n");
MetadataRetrieve meta = getMetadataRetrieve();
if (meta == null) {
throw new FormatException("MetadataRetrieve is null. " +
"Call setMetadataRetrieve(MetadataRetrieve) before calling " +
"saveImage(Image, boolean).");
}
String order = meta.getPixelsDimensionOrder(series, 0);
int x = meta.getPixelsSizeX(series, 0).intValue();
int y = meta.getPixelsSizeY(series, 0).intValue();
int z = meta.getPixelsSizeZ(series, 0).intValue();
int c = meta.getPixelsSizeC(series, 0).intValue();
int t = meta.getPixelsSizeT(series, 0).intValue();
int pixelType =
FormatTools.pixelTypeFromString(meta.getPixelsPixelType(series, 0));
StringBuffer dimOrder = new StringBuffer();
int[] sizes = new int[6];
int nextSize = 0;
sizes[nextSize++] = 8 * FormatTools.getBytesPerPixel(pixelType);
if (byteData.length > 1) {
dimOrder.append("ch\t");
sizes[nextSize++] = c;
}
for (int i=0; i<order.length(); i++) {
if (order.charAt(i) == 'C' && byteData.length == 1) {
dimOrder.append("ch");
sizes[nextSize++] = c;
}
else {
if (order.charAt(i) == 'X') sizes[nextSize++] = x;
else if (order.charAt(i) == 'Y') sizes[nextSize++] = y;
else if (order.charAt(i) == 'Z') sizes[nextSize++] = z;
else if (order.charAt(i) == 'T') sizes[nextSize++] = t;
dimOrder.append(String.valueOf(order.charAt(i)).toLowerCase());
}
dimOrder.append("\t");
}
out.writeBytes("layout\torder\tbits\t" + dimOrder.toString() + "\n");
out.writeBytes("layout\tsizes\t");
for (int i=0; i<sizes.length; i++) {
out.writeBytes(sizes[i] + "\t");
if (i == sizes.length - 1) out.writeBytes("\n");
}
boolean signed = pixelType == FormatTools.INT8 ||
pixelType == FormatTools.INT16 || pixelType == FormatTools.INT32;
out.writeBytes("representation\tformat\t" +
(pixelType == FormatTools.FLOAT ? "real\n" : "integer\n"));
out.writeBytes("representation\tsign\t" +
(signed ? "signed\n" : "unsigned\n"));
out.writeBytes("representation\tcompression\tuncompressed\n");
out.writeBytes("representation\tbyte_order\t");
for (int i=0; i<sizes[0]/8; i++) {
out.writeBytes(((sizes[0] / 8) - i) + "\t");
}
out.writeBytes("\nparameter\tscale\t1.000000\t");
StringTokenizer st = new StringTokenizer(dimOrder.toString(), "\t");
StringBuffer units = new StringBuffer();
while (st.hasMoreTokens()) {
String token = st.nextToken();
Number value = null;
if (token.equals("x")) {
value = meta.getDimensionsPhysicalSizeX(0, 0);
units.append("micrometers\t");
}
else if (token.equals("y")) {
value = meta.getDimensionsPhysicalSizeY(0, 0);
units.append("micrometers\t");
}
else if (token.equals("z")) {
value = meta.getDimensionsPhysicalSizeZ(0, 0);
units.append("micrometers\t");
}
else if (token.equals("t")) {
value = meta.getDimensionsTimeIncrement(0, 0);
units.append("seconds\t");
}
else if (token.equals("ch")) {
value = meta.getDimensionsWaveIncrement(0, 0);
units.append("nm\t");
}
if (value == null) out.writeBytes("1.000000\t");
else out.writeBytes(value + "\t");
}
out.writeBytes("\nparameter\tunits\tbits\t" + units.toString() + "\n");
out.writeBytes("\nend\n");
}
if (byteData.length == 1) out.write(byteData[0]);
else {
for (int pixel=0; pixel<byteData[0].length/bytesPerPixel; pixel++) {
for (int channel=0; channel<byteData.length; channel++) {
out.write(byteData[channel], pixel*bytesPerPixel, bytesPerPixel);
}
}
}
if (last) close();
}
| public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getPixelBytes(img, false);
int bytesPerPixel =
FormatTools.getBytesPerPixel(ImageTools.getPixelType(img));
if (!initialized) {
initialized = true;
out = new RandomAccessFile(currentId, "rw");
out.writeBytes("\t\n");
out.writeBytes("ics_version\t2.0\n");
out.writeBytes("filename\t" + currentId + "\n");
out.writeBytes("layout\tparameters\t6\n");
MetadataRetrieve meta = getMetadataRetrieve();
if (meta == null) {
throw new FormatException("MetadataRetrieve is null. " +
"Call setMetadataRetrieve(MetadataRetrieve) before calling " +
"saveImage(Image, boolean).");
}
String order = meta.getPixelsDimensionOrder(series, 0);
int x = meta.getPixelsSizeX(series, 0).intValue();
int y = meta.getPixelsSizeY(series, 0).intValue();
int z = meta.getPixelsSizeZ(series, 0).intValue();
int c = meta.getPixelsSizeC(series, 0).intValue();
int t = meta.getPixelsSizeT(series, 0).intValue();
int pixelType =
FormatTools.pixelTypeFromString(meta.getPixelsPixelType(series, 0));
StringBuffer dimOrder = new StringBuffer();
int[] sizes = new int[6];
int nextSize = 0;
sizes[nextSize++] = 8 * FormatTools.getBytesPerPixel(pixelType);
if (byteData.length > 1) {
dimOrder.append("ch\t");
sizes[nextSize++] = c;
}
for (int i=0; i<order.length(); i++) {
if (order.charAt(i) == 'C' && byteData.length == 1) {
dimOrder.append("ch");
sizes[nextSize++] = c;
}
else {
if (order.charAt(i) == 'X') sizes[nextSize++] = x;
else if (order.charAt(i) == 'Y') sizes[nextSize++] = y;
else if (order.charAt(i) == 'Z') sizes[nextSize++] = z;
else if (order.charAt(i) == 'T') sizes[nextSize++] = t;
if (order.charAt(i) != 'C') {
dimOrder.append(String.valueOf(order.charAt(i)).toLowerCase());
}
}
dimOrder.append("\t");
}
out.writeBytes("layout\torder\tbits\t" + dimOrder.toString() + "\n");
out.writeBytes("layout\tsizes\t");
for (int i=0; i<sizes.length; i++) {
out.writeBytes(sizes[i] + "\t");
if (i == sizes.length - 1) out.writeBytes("\n");
}
boolean signed = pixelType == FormatTools.INT8 ||
pixelType == FormatTools.INT16 || pixelType == FormatTools.INT32;
out.writeBytes("representation\tformat\t" +
(pixelType == FormatTools.FLOAT ? "real\n" : "integer\n"));
out.writeBytes("representation\tsign\t" +
(signed ? "signed\n" : "unsigned\n"));
out.writeBytes("representation\tcompression\tuncompressed\n");
out.writeBytes("representation\tbyte_order\t");
for (int i=0; i<sizes[0]/8; i++) {
out.writeBytes(((sizes[0] / 8) - i) + "\t");
}
out.writeBytes("\nparameter\tscale\t1.000000\t");
StringTokenizer st = new StringTokenizer(dimOrder.toString(), "\t");
StringBuffer units = new StringBuffer();
while (st.hasMoreTokens()) {
String token = st.nextToken();
Number value = null;
if (token.equals("x")) {
value = meta.getDimensionsPhysicalSizeX(0, 0);
units.append("micrometers\t");
}
else if (token.equals("y")) {
value = meta.getDimensionsPhysicalSizeY(0, 0);
units.append("micrometers\t");
}
else if (token.equals("z")) {
value = meta.getDimensionsPhysicalSizeZ(0, 0);
units.append("micrometers\t");
}
else if (token.equals("t")) {
value = meta.getDimensionsTimeIncrement(0, 0);
units.append("seconds\t");
}
else if (token.equals("ch")) {
value = meta.getDimensionsWaveIncrement(0, 0);
units.append("nm\t");
}
if (value == null) out.writeBytes("1.000000\t");
else out.writeBytes(value + "\t");
}
out.writeBytes("\nparameter\tunits\tbits\t" + units.toString() + "\n");
out.writeBytes("\nend\n");
}
if (byteData.length == 1) out.write(byteData[0]);
else {
for (int pixel=0; pixel<byteData[0].length/bytesPerPixel; pixel++) {
for (int channel=0; channel<byteData.length; channel++) {
out.write(byteData[channel], pixel*bytesPerPixel, bytesPerPixel);
}
}
}
if (last) close();
}
|
diff --git a/src/mod_AdditionalBuildcraftObjects.java b/src/mod_AdditionalBuildcraftObjects.java
index de601a2..c9db440 100644
--- a/src/mod_AdditionalBuildcraftObjects.java
+++ b/src/mod_AdditionalBuildcraftObjects.java
@@ -1,248 +1,248 @@
/**
* Copyright (C) 2011 Flow86
*
* AdditionalBuildcraftObjects is open-source.
*
* It is distributed under the terms of my Open Source License.
* It grants rights to read, modify, compile or run the code.
* It does *NOT* grant the right to redistribute this software or its
* modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*/
package net.minecraft.src;
import net.minecraft.src.AdditionalBuildcraftObjects.BlockABOPipe;
import net.minecraft.src.AdditionalBuildcraftObjects.ItemABOPipe;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsBounce;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsCompactor;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsCrossover;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsExtraction;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsInsertion;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeItemsRoundRobin;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeLiquidsBalance;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeLiquidsGoldenIron;
import net.minecraft.src.AdditionalBuildcraftObjects.PipeLiquidsValve;
import net.minecraft.src.AdditionalBuildcraftObjects.PipePowerSwitch;
import net.minecraft.src.buildcraft.core.CoreProxy;
import net.minecraft.src.buildcraft.core.Utils;
import net.minecraft.src.buildcraft.transport.Pipe;
import net.minecraft.src.forge.ICustomItemRenderer;
import net.minecraft.src.forge.MinecraftForgeClient;
import org.lwjgl.opengl.GL11;
/**
* @author Flow86
*
*/
public class mod_AdditionalBuildcraftObjects extends BaseModMp implements ICustomItemRenderer {
private static boolean initialized = false;
public static mod_AdditionalBuildcraftObjects instance;
@MLProp(min = 0.0D, max = 255.0D)
public static int blockABOPipeID = 200;
public static Block blockABOPipe = null;
//@MLProp(min = 0.0D, max = 255.0D)
//public static int blockRedstonePowerConverterID = 201;
//public static Block blockRedstonePowerConverter = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeLiquidsValveID = 10200;
public static Item pipeLiquidsValve = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeLiquidsGoldenIronID = 10201;
public static Item pipeLiquidsGoldenIron = null;
//@MLProp(min = 256.0D, max = 32000.0D)
//public static int pipeLiquidsFlowMeterID = 10202;
//public static Item pipeLiquidsFlowMeter = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeLiquidsBalanceID = 10203;
public static Item pipeLiquidsBalance = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsRoundRobinID = 10300;
public static Item pipeItemsRoundRobin = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsCompactorID = 10301;
public static Item pipeItemsCompactor = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsInsertionID = 10302;
public static Item pipeItemsInsertion = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsExtractionID = 10303;
public static Item pipeItemsExtraction = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsBounceID = 10304;
public static Item pipeItemsBounce = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipeItemsCrossoverID = 10305;
public static Item pipeItemsCrossover = null;
@MLProp(min = 256.0D, max = 32000.0D)
public static int pipePowerSwitchID = 10400;
public static Item pipePowerSwitch = null;
public static String customTexture = "/net/minecraft/src/AdditionalBuildcraftObjects/gui/block_textures.png";
// public static String customSprites =
// "/net/minecraft/src/AdditionalBuildcraftObjects/gui/item_textures.png";
/**
*
*/
public mod_AdditionalBuildcraftObjects() {
instance = this;
}
@Override
public void load () {
}
@Override
public void ModsLoaded() {
super.ModsLoaded();
initialize();
}
public void initialize() {
if (initialized) {
return;
}
initialized = true;
mod_BuildCraftCore.initialize();
BuildCraftTransport.initialize();
BuildCraftEnergy.initialize();
MinecraftForgeClient.preloadTexture(customTexture);
blockABOPipe = new BlockABOPipe(blockABOPipeID);
ModLoader.RegisterBlock(blockABOPipe);
ModLoader.RegisterTileEntity(ItemABOPipe.class, "net.minecraft.src.AdditionalBuildcraftObjects.ItemABOPipe");
pipeLiquidsValve = createPipe(pipeLiquidsValveID, PipeLiquidsValve.class, "Valve Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, Block.lever, BuildCraftTransport.pipeLiquidsWood);
pipeLiquidsGoldenIron = createPipe(pipeLiquidsGoldenIronID, PipeLiquidsGoldenIron.class, "Golden Iron Waterproof Pipe", 1,
BuildCraftTransport.pipeLiquidsGold, BuildCraftTransport.pipeLiquidsIron, null);
pipeLiquidsBalance = createPipe(pipeLiquidsBalanceID, PipeLiquidsBalance.class, "Balance Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, new ItemStack(BuildCraftTransport.pipeGate, 1, 2), BuildCraftTransport.pipeLiquidsWood);
pipeItemsRoundRobin = createPipe(pipeItemsRoundRobinID, PipeItemsRoundRobin.class, "RoundRobin Transport Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.gravel, null);
pipeItemsCompactor = createPipe(pipeItemsCompactorID, PipeItemsCompactor.class, "Compactor Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.pistonBase, null);
pipeItemsInsertion = createPipe(pipeItemsInsertionID, PipeItemsInsertion.class, "Insertion Pipe", 1,
BuildCraftTransport.pipeItemsStone, Item.redstone, null);
pipeItemsExtraction = createPipe(pipeItemsExtractionID, PipeItemsExtraction.class, "Extraction Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.planks, null);
pipeItemsBounce = createPipe(pipeItemsBounceID, PipeItemsBounce.class, "Bounce Pipe", 1,
- BuildCraftTransport.pipeItemsStone, Block.pistonBase, null);
+ BuildCraftTransport.pipeItemsStone, Block.cobblestone, null);
pipeItemsCrossover = createPipe(pipeItemsCrossoverID, PipeItemsCrossover.class, "Crossover Pipe", 1,
BuildCraftTransport.pipeItemsStone, BuildCraftTransport.pipeItemsIron, null);
pipePowerSwitch = createPipe(pipePowerSwitchID, PipePowerSwitch.class, "Power Switch Pipe", 1,
BuildCraftTransport.pipePowerGold, Block.lever, null);
}
/**
* @param id
* @param clas
* @param descr
* @param r1
* @param r2
* @param r3
* @return
*/
private static Item createPipe(int id, Class<? extends Pipe> clas, String descr, int count, Object r1, Object r2, Object r3) {
Item res = BlockABOPipe.registerPipe(id, clas);
res.setItemName(clas.getSimpleName());
CoreProxy.addName(res, descr);
CraftingManager craftingmanager = CraftingManager.getInstance();
if (r1 != null && r2 != null && r3 != null) {
craftingmanager.addRecipe(new ItemStack(res, count), new Object[] { "ABC",
Character.valueOf('A'), r1, Character.valueOf('B'), r2, Character.valueOf('C'), r3 });
} else if (r1 != null && r2 != null) {
craftingmanager.addRecipe(new ItemStack(res, count), new Object[] { "AB", Character.valueOf('A'), r1,
Character.valueOf('B'), r2 });
}
MinecraftForgeClient.registerCustomItemRenderer(res.shiftedIndex, mod_AdditionalBuildcraftObjects.instance);
return res;
}
/*
* (non-Javadoc)
*
* @see
* net.minecraft.src.forge.ICustomItemRenderer#renderInventory(net.minecraft
* .src.RenderBlocks, int, int)
*/
@Override
public void renderInventory(RenderBlocks renderblocks, int itemID, int meta) {
Tessellator tessellator = Tessellator.instance;
Block block = blockABOPipe;
int textureID = ((ItemABOPipe) Item.itemsList[itemID]).getTextureIndex();
block.setBlockBounds(Utils.pipeMinPos, 0.0F, Utils.pipeMinPos, Utils.pipeMaxPos, 1.0F, Utils.pipeMaxPos);
block.setBlockBoundsForItemRender();
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, -1F, 0.0F);
renderblocks.renderBottomFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, 1.0F, 0.0F);
renderblocks.renderTopFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, 0.0F, -1F);
renderblocks.renderEastFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, 0.0F, 1.0F);
renderblocks.renderWestFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(-1F, 0.0F, 0.0F);
renderblocks.renderNorthFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(1.0F, 0.0F, 0.0F);
renderblocks.renderSouthFace(block, 0.0D, 0.0D, 0.0D, textureID);
tessellator.draw();
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
/*
* (non-Javadoc)
*
* @see net.minecraft.src.BaseMod#Version()
*/
@Override
public String getVersion() {
return "0.8 (MC 1.0.0, BC 3.0.4)";
}
}
| true | true | public void initialize() {
if (initialized) {
return;
}
initialized = true;
mod_BuildCraftCore.initialize();
BuildCraftTransport.initialize();
BuildCraftEnergy.initialize();
MinecraftForgeClient.preloadTexture(customTexture);
blockABOPipe = new BlockABOPipe(blockABOPipeID);
ModLoader.RegisterBlock(blockABOPipe);
ModLoader.RegisterTileEntity(ItemABOPipe.class, "net.minecraft.src.AdditionalBuildcraftObjects.ItemABOPipe");
pipeLiquidsValve = createPipe(pipeLiquidsValveID, PipeLiquidsValve.class, "Valve Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, Block.lever, BuildCraftTransport.pipeLiquidsWood);
pipeLiquidsGoldenIron = createPipe(pipeLiquidsGoldenIronID, PipeLiquidsGoldenIron.class, "Golden Iron Waterproof Pipe", 1,
BuildCraftTransport.pipeLiquidsGold, BuildCraftTransport.pipeLiquidsIron, null);
pipeLiquidsBalance = createPipe(pipeLiquidsBalanceID, PipeLiquidsBalance.class, "Balance Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, new ItemStack(BuildCraftTransport.pipeGate, 1, 2), BuildCraftTransport.pipeLiquidsWood);
pipeItemsRoundRobin = createPipe(pipeItemsRoundRobinID, PipeItemsRoundRobin.class, "RoundRobin Transport Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.gravel, null);
pipeItemsCompactor = createPipe(pipeItemsCompactorID, PipeItemsCompactor.class, "Compactor Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.pistonBase, null);
pipeItemsInsertion = createPipe(pipeItemsInsertionID, PipeItemsInsertion.class, "Insertion Pipe", 1,
BuildCraftTransport.pipeItemsStone, Item.redstone, null);
pipeItemsExtraction = createPipe(pipeItemsExtractionID, PipeItemsExtraction.class, "Extraction Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.planks, null);
pipeItemsBounce = createPipe(pipeItemsBounceID, PipeItemsBounce.class, "Bounce Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.pistonBase, null);
pipeItemsCrossover = createPipe(pipeItemsCrossoverID, PipeItemsCrossover.class, "Crossover Pipe", 1,
BuildCraftTransport.pipeItemsStone, BuildCraftTransport.pipeItemsIron, null);
pipePowerSwitch = createPipe(pipePowerSwitchID, PipePowerSwitch.class, "Power Switch Pipe", 1,
BuildCraftTransport.pipePowerGold, Block.lever, null);
}
| public void initialize() {
if (initialized) {
return;
}
initialized = true;
mod_BuildCraftCore.initialize();
BuildCraftTransport.initialize();
BuildCraftEnergy.initialize();
MinecraftForgeClient.preloadTexture(customTexture);
blockABOPipe = new BlockABOPipe(blockABOPipeID);
ModLoader.RegisterBlock(blockABOPipe);
ModLoader.RegisterTileEntity(ItemABOPipe.class, "net.minecraft.src.AdditionalBuildcraftObjects.ItemABOPipe");
pipeLiquidsValve = createPipe(pipeLiquidsValveID, PipeLiquidsValve.class, "Valve Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, Block.lever, BuildCraftTransport.pipeLiquidsWood);
pipeLiquidsGoldenIron = createPipe(pipeLiquidsGoldenIronID, PipeLiquidsGoldenIron.class, "Golden Iron Waterproof Pipe", 1,
BuildCraftTransport.pipeLiquidsGold, BuildCraftTransport.pipeLiquidsIron, null);
pipeLiquidsBalance = createPipe(pipeLiquidsBalanceID, PipeLiquidsBalance.class, "Balance Pipe", 1,
BuildCraftTransport.pipeLiquidsWood, new ItemStack(BuildCraftTransport.pipeGate, 1, 2), BuildCraftTransport.pipeLiquidsWood);
pipeItemsRoundRobin = createPipe(pipeItemsRoundRobinID, PipeItemsRoundRobin.class, "RoundRobin Transport Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.gravel, null);
pipeItemsCompactor = createPipe(pipeItemsCompactorID, PipeItemsCompactor.class, "Compactor Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.pistonBase, null);
pipeItemsInsertion = createPipe(pipeItemsInsertionID, PipeItemsInsertion.class, "Insertion Pipe", 1,
BuildCraftTransport.pipeItemsStone, Item.redstone, null);
pipeItemsExtraction = createPipe(pipeItemsExtractionID, PipeItemsExtraction.class, "Extraction Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.planks, null);
pipeItemsBounce = createPipe(pipeItemsBounceID, PipeItemsBounce.class, "Bounce Pipe", 1,
BuildCraftTransport.pipeItemsStone, Block.cobblestone, null);
pipeItemsCrossover = createPipe(pipeItemsCrossoverID, PipeItemsCrossover.class, "Crossover Pipe", 1,
BuildCraftTransport.pipeItemsStone, BuildCraftTransport.pipeItemsIron, null);
pipePowerSwitch = createPipe(pipePowerSwitchID, PipePowerSwitch.class, "Power Switch Pipe", 1,
BuildCraftTransport.pipePowerGold, Block.lever, null);
}
|
diff --git a/src/Person.java b/src/Person.java
index d7d21b1..324b94b 100644
--- a/src/Person.java
+++ b/src/Person.java
@@ -1,90 +1,90 @@
import java.util.Date;
import java.text.DateFormat;
import javax.swing.JOptionPane;
public class Person
{
String navn;
int id;
Sykkel sykkel;
String merknad = "";
Date startTid;
static int nesteNr = 0;
public Person(String navn) {
this.navn = navn;
id = nesteNr++;
}
public int getID() {
return id;
}
public Sykkel getSykkel() {
return sykkel;
}
public boolean godkjent()
{
if (sykkel == null && merknad.equals("")) {
return true;
}
return false;
}
public void setMerknad(Date t, String m) {
DateFormat df = DateFormat.getInstance();
merknad+= df.format(t) + " : " + m + "\n";
JOptionPane.showMessageDialog(null, "F�lgende merknad er registert - " + merknad);
}
public boolean leiSykkel(Sykkel s) {
if(godkjent()) {
sykkel = s;
startTid = new Date();
return true;
}
return false;
}
public int leietid(Date sluttTid) {
long varighet = (sluttTid.getTime() - startTid.getTime());
int varighetTimer = (int) Math.ceil(varighet / 3600000);
return varighetTimer;
}
public void leverInn() {
Date innTid = new Date();
if(leietid(innTid) > Sykkel.getMAXTID()) {
if(leietid(innTid) - 3 == 1 ) {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " time for sent");
}
else {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " timer for sent");
}
- sykkel = null;
}
+ sykkel = null;
}
@Override
public String toString() {
String utskrift = navn + " ID nummer: " + id + "\n";
if(sykkel != null) {
utskrift += "Sykkel id: " + sykkel.getID() + "\n";
}
if(merknad != "") {
utskrift += merknad;
}
return utskrift;
}
}
| false | true | public void leverInn() {
Date innTid = new Date();
if(leietid(innTid) > Sykkel.getMAXTID()) {
if(leietid(innTid) - 3 == 1 ) {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " time for sent");
}
else {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " timer for sent");
}
sykkel = null;
}
}
| public void leverInn() {
Date innTid = new Date();
if(leietid(innTid) > Sykkel.getMAXTID()) {
if(leietid(innTid) - 3 == 1 ) {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " time for sent");
}
else {
setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " timer for sent");
}
}
sykkel = null;
}
|
diff --git a/src/main/java/org/i5y/json/stream/impl/JSONWriterImpl.java b/src/main/java/org/i5y/json/stream/impl/JSONWriterImpl.java
index 538fd02..c784d2b 100644
--- a/src/main/java/org/i5y/json/stream/impl/JSONWriterImpl.java
+++ b/src/main/java/org/i5y/json/stream/impl/JSONWriterImpl.java
@@ -1,353 +1,353 @@
package org.i5y.json.stream.impl;
import java.io.IOException;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Deque;
import org.i5y.json.stream.JSONWriter;
class JSONWriterImpl implements JSONWriter {
public void write(String str) {
try {
writer.write(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(char ch) {
try {
writer.write(ch);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private final Writer writer;
private enum Event {
INPUT_START, INPUT_END, OBJECT_START, OBJECT_END, ARRAY_START, ARRAY_END, PROPERTY_NAME, LITERAL
}
private Event lastEvent = Event.INPUT_START;
private Deque<Wrapper> wrappers = new ArrayDeque<Wrapper>(10);
private enum Wrapper {
Object, Array
};
public JSONWriterImpl(final Writer writer) {
this.writer = writer;
}
@Override
public JSONWriter startObject() {
if (wrappers.isEmpty()) {
write('{');
wrappers.push(Wrapper.Object);
lastEvent = Event.OBJECT_START;
return this;
} else if (startValue("{")) {
wrappers.push(Wrapper.Object);
lastEvent = Event.OBJECT_START;
return this;
}
throw new IllegalStateException();
}
private boolean startValue(String insert) {
if (wrappers.peek() == Wrapper.Object) {
if (lastEvent == Event.PROPERTY_NAME) {
write( ":");
write( insert);
return true;
}
} else if (wrappers.peek() == Wrapper.Array) {
if (lastEvent == Event.ARRAY_END || lastEvent == Event.OBJECT_END
|| lastEvent == Event.LITERAL
|| lastEvent == Event.PROPERTY_NAME) {
write( ",");
write( insert);
return true;
} else if (lastEvent == Event.ARRAY_START) {
write( insert);
return true;
}
}
return false;
}
@Override
public JSONWriter endObject() {
if (wrappers.peek() == Wrapper.Object
&& (lastEvent == Event.OBJECT_START
|| lastEvent == Event.ARRAY_END
|| lastEvent == Event.OBJECT_END
|| lastEvent == Event.LITERAL || lastEvent == Event.PROPERTY_NAME)) {
wrappers.pop();
write('}');
lastEvent = Event.OBJECT_END;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter propertyName(String name) {
if (wrappers.peek() == Wrapper.Object) {
if (lastEvent == Event.ARRAY_END || lastEvent == Event.OBJECT_END
|| lastEvent == Event.LITERAL
|| lastEvent == Event.PROPERTY_NAME) {
write( ",\"");
write( name);
write( "\"");
lastEvent = Event.PROPERTY_NAME;
return this;
} else if (lastEvent == Event.OBJECT_START) {
write( "\"");
write( name);
write( "\"");
lastEvent = Event.PROPERTY_NAME;
return this;
}
}
throw new IllegalStateException();
}
private JSONWriter rawProperty(String name, String encodedLiteral)
{
if (wrappers.peek() == Wrapper.Object) {
if (lastEvent == Event.ARRAY_END || lastEvent == Event.OBJECT_END
|| lastEvent == Event.LITERAL
|| lastEvent == Event.PROPERTY_NAME) {
write( ",\"");
write( name);
write( "\":");
write( encodedLiteral);
lastEvent = Event.LITERAL;
return this;
} else if (lastEvent == Event.OBJECT_START) {
write( "\"");
write( name);
write( "\":");
write( encodedLiteral);
lastEvent = Event.LITERAL;
return this;
}
}
throw new IllegalStateException();
}
@Override
public JSONWriter property(String name, String literal)
{
return rawProperty(name, literal);
}
@Override
public JSONWriter property(String name, int literal) {
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, long literal) {
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, BigInteger literal)
{
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, float literal)
{
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, double literal)
{
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, BigDecimal literal)
{
return rawProperty(name, "" + literal);
}
@Override
public JSONWriter property(String name, boolean literal)
{
return rawProperty(name, Boolean.toString(literal));
}
@Override
public JSONWriter nullProperty(String name) {
return rawProperty(name, "null");
}
@Override
public JSONWriter literal(String literal) {
StringBuilder sb = new StringBuilder(literal.length() + 2);
sb.append('\"');
for (int i = 0; i < literal.length(); i++) {
char c = literal.charAt(i);
switch (c) {
case '\"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
- case '/': sb.append("\\/"); break;
+ //case '/': sb.append("\\/"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c >= 0 && c <= 0x1f) {
// Need to encode...
sb.append("\\u");
String hex = Integer.toHexString(c);
switch (hex.length()) {
case 1: sb.append('0');
case 2: sb.append('0');
case 3: sb.append('0');
}
sb.append(hex);
} else {
// For the moment, ignore the high codepoint stuff
sb.append(c);
}
}
}
sb.append('\"');
if (startValue(sb.toString())) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(int literal) {
if (startValue(Integer.toString(literal))) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(long literal) {
if (startValue(Long.toString(literal))) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(BigInteger literal) {
if (startValue(literal.toString())) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(float literal) {
if (startValue(Float.toString(literal))) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(double literal) {
if (startValue(Double.toString(literal))) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(BigDecimal literal) {
if (startValue(literal.toString())) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter nullLiteral() {
if (startValue("null")) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter literal(boolean literal) {
if (startValue(Boolean.toString(literal))) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter startArray() {
if (wrappers.isEmpty()) {
write('[');
wrappers.push(Wrapper.Array);
lastEvent = Event.ARRAY_START;
return this;
} else if (startValue("[")) {
wrappers.push(Wrapper.Array);
lastEvent = Event.ARRAY_START;
return this;
}
throw new IllegalStateException();
}
@Override
public JSONWriter endArray(){
if (wrappers.peek() == Wrapper.Array
&& (lastEvent == Event.ARRAY_START
|| lastEvent == Event.ARRAY_END
|| lastEvent == Event.OBJECT_END
|| lastEvent == Event.LITERAL || lastEvent == Event.PROPERTY_NAME)) {
wrappers.pop();
write(']');
lastEvent = Event.ARRAY_END;
return this;
}
throw new IllegalStateException();
}
@Override
public void flush()throws IOException{
writer.flush();
}
@Override
public void close() throws IOException{
flush();
writer.close();
}
}
| true | true | public JSONWriter literal(String literal) {
StringBuilder sb = new StringBuilder(literal.length() + 2);
sb.append('\"');
for (int i = 0; i < literal.length(); i++) {
char c = literal.charAt(i);
switch (c) {
case '\"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '/': sb.append("\\/"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c >= 0 && c <= 0x1f) {
// Need to encode...
sb.append("\\u");
String hex = Integer.toHexString(c);
switch (hex.length()) {
case 1: sb.append('0');
case 2: sb.append('0');
case 3: sb.append('0');
}
sb.append(hex);
} else {
// For the moment, ignore the high codepoint stuff
sb.append(c);
}
}
}
sb.append('\"');
if (startValue(sb.toString())) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
| public JSONWriter literal(String literal) {
StringBuilder sb = new StringBuilder(literal.length() + 2);
sb.append('\"');
for (int i = 0; i < literal.length(); i++) {
char c = literal.charAt(i);
switch (c) {
case '\"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
//case '/': sb.append("\\/"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c >= 0 && c <= 0x1f) {
// Need to encode...
sb.append("\\u");
String hex = Integer.toHexString(c);
switch (hex.length()) {
case 1: sb.append('0');
case 2: sb.append('0');
case 3: sb.append('0');
}
sb.append(hex);
} else {
// For the moment, ignore the high codepoint stuff
sb.append(c);
}
}
}
sb.append('\"');
if (startValue(sb.toString())) {
lastEvent = Event.LITERAL;
return this;
}
throw new IllegalStateException();
}
|
diff --git a/spring-batch-execution/src/main/java/org/springframework/batch/execution/bootstrap/support/SimpleCommandLineJobRunner.java b/spring-batch-execution/src/main/java/org/springframework/batch/execution/bootstrap/support/SimpleCommandLineJobRunner.java
index 25300c5f5..4e3dbe651 100644
--- a/spring-batch-execution/src/main/java/org/springframework/batch/execution/bootstrap/support/SimpleCommandLineJobRunner.java
+++ b/spring-batch-execution/src/main/java/org/springframework/batch/execution/bootstrap/support/SimpleCommandLineJobRunner.java
@@ -1,301 +1,300 @@
/*
* Copyright 2006-2007 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.springframework.batch.execution.bootstrap.support;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.domain.Job;
import org.springframework.batch.core.domain.JobIdentifier;
import org.springframework.batch.core.domain.NoSuchJobException;
import org.springframework.batch.core.executor.ExitCodeExceptionClassifier;
import org.springframework.batch.core.runtime.JobIdentifierFactory;
import org.springframework.batch.execution.launch.JobLauncher;
import org.springframework.batch.execution.runtime.ScheduledJobIdentifierFactory;
import org.springframework.batch.execution.step.simple.SimpleExitCodeExceptionClassifier;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.SingletonBeanFactoryLocator;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.Assert;
/**
* <p>
* Basic launcher for starting jobs from the command line. In general, it is
* assumed that this launcher will primarily be used to start a job via a script
* from an Enterprise Scheduler. Therefore, exit codes are mapped to integers so
* that schedulers can use the returned values to determine the next course of
* action. The returned values can also be useful to operations teams in
* determining what should happen upon failure. For example, a returned code of
* 5 might mean that some resource wasn't available and the job should be
* restarted. However, a code of 10 might mean that something critical has
* happened and the issue should be escalated.
* </p>
*
* <p>
* With any launch of a batch job within Spring Batch, a Spring context
* containing the Job and the 'Execution Environment' has to be created. This
* command line launcher can be used to load that context from a single
* location. It can also be used to first load the execution environment context
* via a {@link ContextSingletonBeanFactoryLocator}. This will then be used as
* the parent to the Job context. All dependencies of the launcher will then be
* satisfied by autowiring by type from the combined application context.
* Default values are provided for all fields except the {@link JobLauncher}.
* Therefore, if autowiring fails to set it (it should be noted that dependency
* checking is disabled because most of the fields have default values and thus
* don't require dependencies to be fulfilled via autowiring) then an exception
* will be thrown. It should also be noted that even if an exception is thrown
* by this class, it will be mapped to an integer and returned.
* </p>
*
* <p>
* Notice a property is available to set the {@link SystemExiter}. This class
* is used to exit from the main method, rather than calling System.exit()
* directly. This is because unit testing a class the calls System.exit() is
* impossible without kicking off the test within a new Jvm, which it is
* possible to do, however it is a complex solution, much more so than
* strategizing the exiter.
* </p>
*
* <p>
* VM Arguments vs. Program arguments: Because all of the arguments to the main
* method are optional, System properties (VM arguments) are used (@see
* {@link #main(String[])}).
*
* @author Dave Syer
* @author Lucas Ward
* @since 2.1
*/
public class SimpleCommandLineJobRunner {
protected static final Log logger = LogFactory.getLog(SimpleCommandLineJobRunner.class);
/**
* The default path to the job configuration.
*/
public static final String DEFAULT_JOB_CONFIGURATION_PATH = "job-configuration.xml";
public static final String JOB_CONFIGURATION_PATH_KEY = "job.configuration.path";
public static final String JOB_NAME_KEY = "job.name";
public static final String BATCH_EXECUTION_ENVIRONMENT_KEY = "batch.execution.environment.key";
public static final String BEAN_REF_CONTEXT_KEY = "bean.ref.context";
private JobIdentifierFactory jobIdentifierFactory = new ScheduledJobIdentifierFactory();
private BeanFactoryLocator beanFactoryLocator;
private ExitCodeMapper exitCodeMapper = new SimpleJvmExitCodeMapper();
private ExitCodeExceptionClassifier exceptionClassifier = new SimpleExitCodeExceptionClassifier();
private JobLauncher launcher;
private SystemExiter systemExiter = new JvmSystemExiter();
private String defaultJobName;
public SimpleCommandLineJobRunner(String beanRefContextPath) {
if (beanRefContextPath == null) {
return;
}
beanFactoryLocator = ContextSingletonBeanFactoryLocator.getInstance(beanRefContextPath);
}
/**
* Setter for the name of the {@link Job} that this launcher will run.
*
* @param jobName the job name to set
*/
public void setDefaultJobName(String defaultJobName) {
this.defaultJobName = defaultJobName;
}
/**
* Setter for {@link JobIdentifierFactory}.
*
* @param jobIdentifierFactory the {@link JobIdentifierFactory} to set
*/
public void setJobIdentifierFactory(JobIdentifierFactory jobIdentifierFactory) {
this.jobIdentifierFactory = jobIdentifierFactory;
}
/**
* Injection setter for the {@link JobLauncher}.
*
* @param launcher the launcher to set
*/
public void setLauncher(JobLauncher launcher) {
this.launcher = launcher;
}
/**
* Injection setter for the {@link ExitCodeExceptionClassifier}
*
* @param exceptionClassifier
*/
public void setExceptionClassifier(ExitCodeExceptionClassifier exceptionClassifier) {
this.exceptionClassifier = exceptionClassifier;
}
/**
* Injection setter for the {@link JvmExitCodeMapper}.
*
* @param exitCodeMapper the exitCodeMapper to set
*/
public void setExitCodeMapper(ExitCodeMapper exitCodeMapper) {
this.exitCodeMapper = exitCodeMapper;
}
/**
* Injection setter for the {@link SystemExiter}.
*
* @param systemExitor
*/
public void setSystemExiter(SystemExiter systemExitor) {
this.systemExiter = systemExitor;
}
/**
* Delegate to the exiter to (possibly) exit the VM gracefully.
*
* @param status
*/
public void exit(int status) {
systemExiter.exit(status);
}
/**
* @param path the path to a Spring context configuration for this job
* @param jobName the name of the job execution to use
* @parm parentKey the key to be loaded by
* ContextSingletonBeanFactoryLocator and used as the parent context.
* @throws NoSuchJobException
* @throws IllegalStateException if JobLauncher is not autowired by the
* ApplicationContext
*/
int start(String path, String jobName, String parentKey) {
ExitStatus status = ExitStatus.FAILED;
ClassPathXmlApplicationContext context = null;
try {
ConfigurableApplicationContext parent = null;
if (beanFactoryLocator != null) {
parent = (ConfigurableApplicationContext) beanFactoryLocator.useBeanFactory(parentKey).getFactory();
parent.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
if (!path.endsWith(".xml")) {
path = path + ".xml";
}
context = new ClassPathXmlApplicationContext(new String[] { path }, parent);
context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
Assert.state(launcher != null, "JobLauncher must be provided in the parent ApplicationContext"
- + ", check the context created within classpath*:beanRefContext.xml to ensure a JobLauncher"
- + " is declared");
+ + ", check the context to ensure a JobLauncher is declared");
if (jobName == null) {
String[] names = context.getBeanNamesForType(Job.class);
if (names.length == 1) {
Job job = (Job) context.getBean(names[0]);
jobName = job.getName();
}
}
if (jobName == null) {
jobName = defaultJobName;
}
if (jobName == null) {
throw new NoSuchJobException("Null job name cannot be located.");
}
JobIdentifier runtimeInformation = jobIdentifierFactory.getJobIdentifier(jobName);
if (!launcher.isRunning()) {
status = launcher.run(runtimeInformation).getExitStatus();
}
}
catch (NoSuchJobException e) {
logger.fatal("Could not locate JobConfiguration \"" + jobName + "\"", e);
status = new ExitStatus(false, ExitCodeMapper.NO_SUCH_JOB);
}
catch (Throwable t) {
logger.fatal(t);
status = exceptionClassifier.classifyForExitCode(t);
}
finally {
if (context != null) {
try {
context.stop();
}
finally {
context.close();
}
}
}
return exitCodeMapper.getExitCode(status.getExitCode());
}
/**
* Launch a batch job using a {@link SimpleCommandLineJobRunner}. Creates a
* new Spring context for the job execution, and uses a common parent for
* all such contexts. No exception are thrown from this method, rather
* exceptions are logged and an integer returned through the exit status in
* a {@link JvmSystemExiter} (which can be overridden by defining one in the
* Spring context).
*
* @param args
* <ul>
* <li>-Djob.configuration.path: the classpath location of the
* JobConfiguration to use
* <li>-Djob.name: job name to be passed to the {@link JobLauncher}
* <li>-Dbatch.execution.environment.key: the key in beanRefContext.xml
* used to load the execution environment which will be the parent context
* for the job execution (mandatory if -Dbean.ref.context is specified).
* <li>-Dbean.ref.context: the location for beanRefContext.xml (optional,
* default is to only use the context specified in the
* job.configuration.path) (@see {@link SingletonBeanFactoryLocator}).</li>
* </ul>
*/
public static void main(String[] args) {
String path = System.getProperty(JOB_CONFIGURATION_PATH_KEY, DEFAULT_JOB_CONFIGURATION_PATH);
String name = System.getProperty(JOB_NAME_KEY);
String beanRefContextPath = System.getProperty(BEAN_REF_CONTEXT_KEY);
String parentKey = System.getProperty(BATCH_EXECUTION_ENVIRONMENT_KEY);
Assert.state(!(beanRefContextPath == null && parentKey != null), "If you specify the "
+ BATCH_EXECUTION_ENVIRONMENT_KEY + " you must also specify a path for the " + BEAN_REF_CONTEXT_KEY);
SimpleCommandLineJobRunner command = new SimpleCommandLineJobRunner(beanRefContextPath);
int result = command.start(path, name, parentKey);
command.exit(result);
}
}
| true | true | int start(String path, String jobName, String parentKey) {
ExitStatus status = ExitStatus.FAILED;
ClassPathXmlApplicationContext context = null;
try {
ConfigurableApplicationContext parent = null;
if (beanFactoryLocator != null) {
parent = (ConfigurableApplicationContext) beanFactoryLocator.useBeanFactory(parentKey).getFactory();
parent.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
if (!path.endsWith(".xml")) {
path = path + ".xml";
}
context = new ClassPathXmlApplicationContext(new String[] { path }, parent);
context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
Assert.state(launcher != null, "JobLauncher must be provided in the parent ApplicationContext"
+ ", check the context created within classpath*:beanRefContext.xml to ensure a JobLauncher"
+ " is declared");
if (jobName == null) {
String[] names = context.getBeanNamesForType(Job.class);
if (names.length == 1) {
Job job = (Job) context.getBean(names[0]);
jobName = job.getName();
}
}
if (jobName == null) {
jobName = defaultJobName;
}
if (jobName == null) {
throw new NoSuchJobException("Null job name cannot be located.");
}
JobIdentifier runtimeInformation = jobIdentifierFactory.getJobIdentifier(jobName);
if (!launcher.isRunning()) {
status = launcher.run(runtimeInformation).getExitStatus();
}
}
catch (NoSuchJobException e) {
logger.fatal("Could not locate JobConfiguration \"" + jobName + "\"", e);
status = new ExitStatus(false, ExitCodeMapper.NO_SUCH_JOB);
}
catch (Throwable t) {
logger.fatal(t);
status = exceptionClassifier.classifyForExitCode(t);
}
finally {
if (context != null) {
try {
context.stop();
}
finally {
context.close();
}
}
}
return exitCodeMapper.getExitCode(status.getExitCode());
}
| int start(String path, String jobName, String parentKey) {
ExitStatus status = ExitStatus.FAILED;
ClassPathXmlApplicationContext context = null;
try {
ConfigurableApplicationContext parent = null;
if (beanFactoryLocator != null) {
parent = (ConfigurableApplicationContext) beanFactoryLocator.useBeanFactory(parentKey).getFactory();
parent.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
if (!path.endsWith(".xml")) {
path = path + ".xml";
}
context = new ClassPathXmlApplicationContext(new String[] { path }, parent);
context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
Assert.state(launcher != null, "JobLauncher must be provided in the parent ApplicationContext"
+ ", check the context to ensure a JobLauncher is declared");
if (jobName == null) {
String[] names = context.getBeanNamesForType(Job.class);
if (names.length == 1) {
Job job = (Job) context.getBean(names[0]);
jobName = job.getName();
}
}
if (jobName == null) {
jobName = defaultJobName;
}
if (jobName == null) {
throw new NoSuchJobException("Null job name cannot be located.");
}
JobIdentifier runtimeInformation = jobIdentifierFactory.getJobIdentifier(jobName);
if (!launcher.isRunning()) {
status = launcher.run(runtimeInformation).getExitStatus();
}
}
catch (NoSuchJobException e) {
logger.fatal("Could not locate JobConfiguration \"" + jobName + "\"", e);
status = new ExitStatus(false, ExitCodeMapper.NO_SUCH_JOB);
}
catch (Throwable t) {
logger.fatal(t);
status = exceptionClassifier.classifyForExitCode(t);
}
finally {
if (context != null) {
try {
context.stop();
}
finally {
context.close();
}
}
}
return exitCodeMapper.getExitCode(status.getExitCode());
}
|
diff --git a/ui/fcp/FCPInterface.java b/ui/fcp/FCPInterface.java
index a03ed502..d5fab66e 100644
--- a/ui/fcp/FCPInterface.java
+++ b/ui/fcp/FCPInterface.java
@@ -1,386 +1,388 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WoT.ui.fcp;
import java.net.MalformedURLException;
import java.util.Iterator;
import plugins.WoT.Identity;
import plugins.WoT.OwnIdentity;
import plugins.WoT.Score;
import plugins.WoT.Trust;
import plugins.WoT.WoT;
import plugins.WoT.exceptions.InvalidParameterException;
import plugins.WoT.exceptions.NotInTrustTreeException;
import plugins.WoT.exceptions.NotTrustedException;
import plugins.WoT.exceptions.UnknownIdentityException;
import plugins.WoT.introduction.IntroductionPuzzle;
import plugins.WoT.introduction.IntroductionServer;
import com.db4o.ObjectSet;
import freenet.node.FSParseException;
import freenet.pluginmanager.FredPluginFCP;
import freenet.pluginmanager.PluginNotFoundException;
import freenet.pluginmanager.PluginReplySender;
import freenet.support.Logger;
import freenet.support.SimpleFieldSet;
import freenet.support.api.Bucket;
/**
* @author xor ([email protected]), Julien Cornuwel ([email protected])
*/
public final class FCPInterface implements FredPluginFCP {
private final WoT mWoT;
public FCPInterface(final WoT myWoT) {
mWoT = myWoT;
}
public void handle(final PluginReplySender replysender, final SimpleFieldSet params, final Bucket data, final int accesstype) {
try {
final String message = params.get("Message");
if (message.equals("CreateIdentity")) {
replysender.send(handleCreateIdentity(params), data);
} else if (message.equals("SetTrust")) {
replysender.send(handleSetTrust(params), data);
} else if (message.equals("AddIdentity")) {
replysender.send(handleAddIdentity(params), data);
} else if (message.equals("GetIdentity")) {
replysender.send(handleGetIdentity(params), data);
} else if (message.equals("GetOwnIdentities")) {
replysender.send(handleGetOwnIdentities(params), data);
} else if (message.equals("GetIdentitiesByScore")) {
replysender.send(handleGetIdentitiesByScore(params), data);
} else if (message.equals("GetTrusters")) {
replysender.send(handleGetTrusters(params), data);
} else if (message.equals("GetTrustees")) {
replysender.send(handleGetTrustees(params), data);
} else if (message.equals("AddContext")) {
replysender.send(handleAddContext(params), data);
} else if (message.equals("RemoveContext")) {
replysender.send(handleRemoveContext(params), data);
} else if (message.equals("SetProperty")) {
replysender.send(handleSetProperty(params), data);
} else if (message.equals("GetProperty")) {
replysender.send(handleGetProperty(params), data);
} else if (message.equals("RemoveProperty")) {
replysender.send(handleRemoveProperty(params), data);
} else {
throw new Exception("Unknown message (" + message + ")");
}
} catch (final Exception e) {
Logger.error(this, e.toString());
try {
replysender.send(errorMessageFCP(params.get("Message"), e), data);
} catch (final PluginNotFoundException e1) {
Logger.normal(this, "Connection to request sender lost", e1);
}
}
}
private String getMandatoryParameter(final SimpleFieldSet sfs, final String name) throws InvalidParameterException {
final String result = sfs.get(name);
if(result == null)
throw new IllegalArgumentException("Missing mandatory parameter: " + name);
return result;
}
private SimpleFieldSet handleCreateIdentity(final SimpleFieldSet params)
throws InvalidParameterException, FSParseException, MalformedURLException {
OwnIdentity identity;
final String identityNickname = getMandatoryParameter(params, "Nickname");
final String identityContext = getMandatoryParameter(params, "Context");
final String identityPublishesTrustListStr = getMandatoryParameter(params, "PublishTrustList");
final boolean identityPublishesTrustList = identityPublishesTrustListStr.equals("true") || identityPublishesTrustListStr.equals("yes");
final String identityRequestURI = params.get("RequestURI");
final String identityInsertURI = params.get("InsertURI");
/* The constructor will throw for us if one is missing. Do not use "||" because that would lead to creation of a new URI if the
* user forgot one of the URIs and the user would not get notified about that. */
+ synchronized(mWoT) { /* Preserve the locking order to prevent future deadlocks */
if (identityRequestURI == null && identityInsertURI == null) {
identity = mWoT.createOwnIdentity(identityNickname, identityPublishesTrustList, identityContext);
} else {
identity = mWoT.createOwnIdentity(identityInsertURI, identityRequestURI, identityNickname, identityPublishesTrustList,
identityContext);
}
if (params.get("PublishIntroductionPuzzles") != null && params.getBoolean("PublishIntroductionPuzzles"))
{
if(!identityPublishesTrustList)
throw new InvalidParameterException("An identity cannot publish introduction puzzles if it does not publish its trust list.");
synchronized(identity) {
// TODO: Create a function for those?
try {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
mWoT.storeAndCommit(identity);
}
catch(RuntimeException e) {
mWoT.deleteIdentity(identity);
throw e;
}
}
}
+ }
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "IdentityCreated");
sfs.putOverwrite("ID", identity.getID());
sfs.putOverwrite("InsertURI", identity.getInsertURI().toString());
sfs.putOverwrite("RequestURI", identity.getRequestURI().toString());
return sfs;
}
private SimpleFieldSet handleSetTrust(final SimpleFieldSet params)
throws InvalidParameterException, NumberFormatException, UnknownIdentityException
{
final String trusterID = getMandatoryParameter(params, "Truster");
final String trusteeID = getMandatoryParameter(params, "Trustee");
final String trustValue = getMandatoryParameter(params, "Value");
final String trustComment = getMandatoryParameter(params, "Comment");
mWoT.setTrust(trusterID, trusteeID, Byte.parseByte(trustValue), trustComment);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "TrustSet");
return sfs;
}
private SimpleFieldSet handleAddIdentity(final SimpleFieldSet params) throws InvalidParameterException, MalformedURLException {
final String requestURI = getMandatoryParameter(params, "RequestURI");
final Identity identity = mWoT.addIdentity(requestURI);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "IdentityAdded");
sfs.putOverwrite("ID", identity.getID());
return sfs;
}
private SimpleFieldSet handleGetIdentity(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String treeOwnerID = getMandatoryParameter(params, "TreeOwner");
final String identityID = getMandatoryParameter(params, "Identity");
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Identity");
synchronized(mWoT) {
final OwnIdentity treeOwner = mWoT.getOwnIdentityByID(treeOwnerID);
final Identity identity = mWoT.getIdentityByID(identityID);
try {
final Trust trust = mWoT.getTrust(treeOwner, identity);
sfs.putOverwrite("Trust", Byte.toString(trust.getValue()));
} catch (final NotTrustedException e1) {
sfs.putOverwrite("Trust", "null");
}
try {
final Score score = mWoT.getScore(treeOwner, identity);
sfs.putOverwrite("Score", Integer.toString(score.getScore()));
sfs.putOverwrite("Rank", Integer.toString(score.getRank()));
} catch (final NotInTrustTreeException e) {
sfs.putOverwrite("Score", "null");
sfs.putOverwrite("Rank", "null");
}
final Iterator<String> contexts = identity.getContexts().iterator();
for(int i = 1; contexts.hasNext(); ++i) {
sfs.putOverwrite("Context" + i, contexts.next());
}
}
return sfs;
}
private SimpleFieldSet handleGetOwnIdentities(final SimpleFieldSet params) {
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "OwnIdentities");
synchronized(mWoT) {
final ObjectSet<OwnIdentity> result = mWoT.getAllOwnIdentities();
for(int i = 1; result.hasNext(); ) {
final OwnIdentity oid = result.next();
sfs.putOverwrite("Identity" + i, oid.getID());
sfs.putOverwrite("RequestURI" + i, oid.getRequestURI().toString());
sfs.putOverwrite("InsertURI" + i, oid.getInsertURI().toString());
sfs.putOverwrite("Nickname" + i, oid.getNickname());
// TODO: Allow the client to select what data he wants
// This is here so you do not forget to do it IN the "if()" if you add an if() around the put() statements to allow selection
++i;
}
}
return sfs;
}
private SimpleFieldSet handleGetIdentitiesByScore(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String treeOwnerID = params.get("TreeOwner");
final String selection = getMandatoryParameter(params, "Selection");
final String context = getMandatoryParameter(params, "Context");
final String selectString = selection.trim();
int select = 0; // TODO: decide about the default value
if (selectString.equals("+")) select = 1;
else if (selectString.equals("-")) select = -1;
else if (selectString.equals("0")) select = 0;
else throw new InvalidParameterException("Unhandled selection value (" + select + ")");
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Identities");
synchronized(mWoT) {
final OwnIdentity treeOwner = treeOwnerID != null ? mWoT.getOwnIdentityByID(treeOwnerID) : null;
final ObjectSet<Score> result = mWoT.getIdentitiesByScore(treeOwner, select);
final boolean getAll = context.equals("");
for(int i = 1; result.hasNext(); ) {
final Score score = result.next();
if(getAll || score.getTarget().hasContext(context)) {
final Identity identity = score.getTarget();
sfs.putOverwrite("Identity" + i, identity.getID());
sfs.putOverwrite("RequestURI" + i, identity.getRequestURI().toString());
sfs.putOverwrite("Nickname" + i, identity.getNickname() != null ? identity.getNickname() : "");
++i;
// TODO: Allow the client to select what data he wants
}
}
}
return sfs;
}
private SimpleFieldSet handleGetTrusters(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String context = getMandatoryParameter(params, "Context");
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Identities");
final boolean getAll = context.equals("");
synchronized(mWoT) {
final ObjectSet<Trust> receivedTrusts = mWoT.getReceivedTrusts(mWoT.getIdentityByID(identityID));
for(int i = 1; receivedTrusts.hasNext(); ) {
final Trust trust = receivedTrusts.next();
if(getAll || trust.getTruster().hasContext(params.get("Context"))) {
sfs.putOverwrite("Identity" + i, trust.getTruster().getID());
sfs.putOverwrite("Value" + i, Byte.toString(trust.getValue()));
sfs.putOverwrite("Comment" + i, trust.getComment());
// TODO: Allow the client to select what data he wants
++i;
}
}
}
return sfs;
}
private SimpleFieldSet handleGetTrustees(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String context = getMandatoryParameter(params, "Context");
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Identities");
final boolean getAll = context.equals("");
synchronized(mWoT) {
final ObjectSet<Trust> givenTrusts = mWoT.getGivenTrusts(mWoT.getIdentityByID(identityID));
for(int i = 1; givenTrusts.hasNext(); ) {
final Trust trust = givenTrusts.next();
if(getAll || trust.getTruster().hasContext(params.get("Context"))) {
sfs.putOverwrite("Identity" + i, trust.getTruster().getID());
sfs.putOverwrite("Value" + i, Byte.toString(trust.getValue()));
sfs.putOverwrite("Comment" + i, trust.getComment());
// TODO: Allow the client to select what data he wants
++i;
}
}
}
return sfs;
}
private SimpleFieldSet handleAddContext(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String context = getMandatoryParameter(params, "Context");
mWoT.addContext(identityID, context);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "ContextAdded");
return sfs;
}
private SimpleFieldSet handleRemoveContext(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String context = getMandatoryParameter(params, "Context");
mWoT.removeContext(identityID, context);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "ContextRemoved");
return sfs;
}
private SimpleFieldSet handleSetProperty(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String propertyName = getMandatoryParameter(params, "Property");
final String propertyValue = getMandatoryParameter(params, "Value");
mWoT.setProperty(identityID, propertyName, propertyValue);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "PropertyAdded");
return sfs;
}
private SimpleFieldSet handleGetProperty(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String propertyName = getMandatoryParameter(params, "Property");
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "PropertyValue");
sfs.putOverwrite("Property", mWoT.getProperty(identityID, propertyName));
return sfs;
}
private SimpleFieldSet handleRemoveProperty(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException {
final String identityID = getMandatoryParameter(params, "Identity");
final String propertyName = getMandatoryParameter(params, "Property");
mWoT.removeProperty(identityID, propertyName);
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "PropertyRemoved");
return sfs;
}
private SimpleFieldSet errorMessageFCP(final String originalMessage, final Exception e) {
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Error");
sfs.putOverwrite("OriginalMessage", originalMessage);
sfs.putOverwrite("Description", (e.getLocalizedMessage() == null) ? "null" : e.getLocalizedMessage());
return sfs;
}
}
| false | true | private SimpleFieldSet handleCreateIdentity(final SimpleFieldSet params)
throws InvalidParameterException, FSParseException, MalformedURLException {
OwnIdentity identity;
final String identityNickname = getMandatoryParameter(params, "Nickname");
final String identityContext = getMandatoryParameter(params, "Context");
final String identityPublishesTrustListStr = getMandatoryParameter(params, "PublishTrustList");
final boolean identityPublishesTrustList = identityPublishesTrustListStr.equals("true") || identityPublishesTrustListStr.equals("yes");
final String identityRequestURI = params.get("RequestURI");
final String identityInsertURI = params.get("InsertURI");
/* The constructor will throw for us if one is missing. Do not use "||" because that would lead to creation of a new URI if the
* user forgot one of the URIs and the user would not get notified about that. */
if (identityRequestURI == null && identityInsertURI == null) {
identity = mWoT.createOwnIdentity(identityNickname, identityPublishesTrustList, identityContext);
} else {
identity = mWoT.createOwnIdentity(identityInsertURI, identityRequestURI, identityNickname, identityPublishesTrustList,
identityContext);
}
if (params.get("PublishIntroductionPuzzles") != null && params.getBoolean("PublishIntroductionPuzzles"))
{
if(!identityPublishesTrustList)
throw new InvalidParameterException("An identity cannot publish introduction puzzles if it does not publish its trust list.");
synchronized(identity) {
// TODO: Create a function for those?
try {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
mWoT.storeAndCommit(identity);
}
catch(RuntimeException e) {
mWoT.deleteIdentity(identity);
throw e;
}
}
}
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "IdentityCreated");
sfs.putOverwrite("ID", identity.getID());
sfs.putOverwrite("InsertURI", identity.getInsertURI().toString());
sfs.putOverwrite("RequestURI", identity.getRequestURI().toString());
return sfs;
}
| private SimpleFieldSet handleCreateIdentity(final SimpleFieldSet params)
throws InvalidParameterException, FSParseException, MalformedURLException {
OwnIdentity identity;
final String identityNickname = getMandatoryParameter(params, "Nickname");
final String identityContext = getMandatoryParameter(params, "Context");
final String identityPublishesTrustListStr = getMandatoryParameter(params, "PublishTrustList");
final boolean identityPublishesTrustList = identityPublishesTrustListStr.equals("true") || identityPublishesTrustListStr.equals("yes");
final String identityRequestURI = params.get("RequestURI");
final String identityInsertURI = params.get("InsertURI");
/* The constructor will throw for us if one is missing. Do not use "||" because that would lead to creation of a new URI if the
* user forgot one of the URIs and the user would not get notified about that. */
synchronized(mWoT) { /* Preserve the locking order to prevent future deadlocks */
if (identityRequestURI == null && identityInsertURI == null) {
identity = mWoT.createOwnIdentity(identityNickname, identityPublishesTrustList, identityContext);
} else {
identity = mWoT.createOwnIdentity(identityInsertURI, identityRequestURI, identityNickname, identityPublishesTrustList,
identityContext);
}
if (params.get("PublishIntroductionPuzzles") != null && params.getBoolean("PublishIntroductionPuzzles"))
{
if(!identityPublishesTrustList)
throw new InvalidParameterException("An identity cannot publish introduction puzzles if it does not publish its trust list.");
synchronized(identity) {
// TODO: Create a function for those?
try {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
mWoT.storeAndCommit(identity);
}
catch(RuntimeException e) {
mWoT.deleteIdentity(identity);
throw e;
}
}
}
}
final SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "IdentityCreated");
sfs.putOverwrite("ID", identity.getID());
sfs.putOverwrite("InsertURI", identity.getInsertURI().toString());
sfs.putOverwrite("RequestURI", identity.getRequestURI().toString());
return sfs;
}
|
diff --git a/src/main/java/be/ugent/intec/gtfsfilter/TransportTypeDaoFilter.java b/src/main/java/be/ugent/intec/gtfsfilter/TransportTypeDaoFilter.java
index a4f1557..fd6f0d7 100644
--- a/src/main/java/be/ugent/intec/gtfsfilter/TransportTypeDaoFilter.java
+++ b/src/main/java/be/ugent/intec/gtfsfilter/TransportTypeDaoFilter.java
@@ -1,183 +1,183 @@
package be.ugent.intec.gtfsfilter;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Frequency;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.ServiceCalendar;
import org.onebusaway.gtfs.model.ServiceCalendarDate;
import org.onebusaway.gtfs.model.ShapePoint;
import org.onebusaway.gtfs.model.Stop;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.GtfsDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.ugent.intec.gtfsfilter.predicates.FrequencyByTripsPredicate;
import be.ugent.intec.gtfsfilter.predicates.ServiceCalendarByServiceIdsPredicate;
import be.ugent.intec.gtfsfilter.predicates.ServiceCalendarDateByServiceIdsPredicate;
import be.ugent.intec.gtfsfilter.predicates.ShapePointsByShapeIdsPredicate;
import be.ugent.intec.gtfsfilter.predicates.StopTimeByRoutesPredicate;
import be.ugent.intec.gtfsfilter.predicates.TripByRoutesPredicate;
import be.ugent.intec.gtfsfilter.transformers.StopTimeToStopFunction;
import be.ugent.intec.gtfsfilter.transformers.TripToServiceIdFunction;
import be.ugent.intec.gtfsfilter.transformers.TripToShapeIdFunction;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.primitives.Ints;
public class TransportTypeDaoFilter extends GtfsDaoFilter {
private static final Logger LOG = LoggerFactory
.getLogger(TransportTypeDaoFilter.class);
public static final int TRAM_TYPE = 0;
private final Set<Route> routes;
private final Set<Stop> stops;
private final Collection<Trip> trips;
private final Collection<StopTime> stoptimes;
private final Set<AgencyAndId> serviceIds;
private final Set<AgencyAndId> shapeIds;
public TransportTypeDaoFilter(GtfsDao dao, final int... transportTypes) {
super(dao);
Preconditions.checkArgument(transportTypes.length > 0);
routes = new HashSet<>();
routes.addAll(Collections2.filter(dao.getAllRoutes(),
new Predicate<Route>() {
List<Integer> list = Ints.asList(transportTypes);
@Override
public boolean apply(Route input) {
- return input.getType() == TRAM_TYPE;
+ return list.contains(input.getType());
}
}));
LOG.info("Filtered down from {} to {} routes", input.getAllRoutes()
.size(), routes.size());
trips = Collections2.filter(super.getAllTrips(),
new TripByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} trips", super.getAllTrips()
.size(), trips.size());
stoptimes = Collections2.filter(super.getAllStopTimes(),
new StopTimeByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} stoptimes", input
.getAllStopTimes().size(), stoptimes.size());
stops = new HashSet<>();
stops.addAll(Collections2.transform(stoptimes,
new StopTimeToStopFunction()));
LOG.info("Filtered down from {} to {} stops", input.getAllStops()
.size(), stops.size());
serviceIds = new HashSet<>();
serviceIds.addAll(Collections2.transform(trips,
new TripToServiceIdFunction()));
LOG.info("Filtered down to {} serviceIds", serviceIds.size());
shapeIds = new HashSet<>();
shapeIds.addAll(Collections2.transform(trips,
new TripToShapeIdFunction()));
LOG.info("Filtered down to {} shapeIds", shapeIds.size());
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllRoutes()
*/
@Override
public Collection<Route> getAllRoutes() {
return routes;
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllTrips()
*/
@Override
public synchronized Collection<Trip> getAllTrips() {
return trips;
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllStopTimes()
*/
@Override
public synchronized Collection<StopTime> getAllStopTimes() {
return stoptimes;
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllStops()
*/
@Override
public Collection<Stop> getAllStops() {
return stops;
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllCalendars()
*/
@Override
public Collection<ServiceCalendar> getAllCalendars() {
return Collections2.filter(super.getAllCalendars(),
new ServiceCalendarByServiceIdsPredicate(serviceIds));
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllCalendarDates()
*/
@Override
public Collection<ServiceCalendarDate> getAllCalendarDates() {
return Collections2.filter(super.getAllCalendarDates(),
new ServiceCalendarDateByServiceIdsPredicate(serviceIds));
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllFrequencies()
*/
@Override
public Collection<Frequency> getAllFrequencies() {
return Collections2.filter(super.getAllFrequencies(),
new FrequencyByTripsPredicate(trips));
}
/*
* (non-Javadoc)
*
* @see be.ugent.intec.gtfsfilter.GtfsDaoFilter#getAllShapePoints()
*/
@Override
public Collection<ShapePoint> getAllShapePoints() {
return Collections2.filter(super.getAllShapePoints(),
new ShapePointsByShapeIdsPredicate(shapeIds));
}
}
| true | true | public TransportTypeDaoFilter(GtfsDao dao, final int... transportTypes) {
super(dao);
Preconditions.checkArgument(transportTypes.length > 0);
routes = new HashSet<>();
routes.addAll(Collections2.filter(dao.getAllRoutes(),
new Predicate<Route>() {
List<Integer> list = Ints.asList(transportTypes);
@Override
public boolean apply(Route input) {
return input.getType() == TRAM_TYPE;
}
}));
LOG.info("Filtered down from {} to {} routes", input.getAllRoutes()
.size(), routes.size());
trips = Collections2.filter(super.getAllTrips(),
new TripByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} trips", super.getAllTrips()
.size(), trips.size());
stoptimes = Collections2.filter(super.getAllStopTimes(),
new StopTimeByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} stoptimes", input
.getAllStopTimes().size(), stoptimes.size());
stops = new HashSet<>();
stops.addAll(Collections2.transform(stoptimes,
new StopTimeToStopFunction()));
LOG.info("Filtered down from {} to {} stops", input.getAllStops()
.size(), stops.size());
serviceIds = new HashSet<>();
serviceIds.addAll(Collections2.transform(trips,
new TripToServiceIdFunction()));
LOG.info("Filtered down to {} serviceIds", serviceIds.size());
shapeIds = new HashSet<>();
shapeIds.addAll(Collections2.transform(trips,
new TripToShapeIdFunction()));
LOG.info("Filtered down to {} shapeIds", shapeIds.size());
}
| public TransportTypeDaoFilter(GtfsDao dao, final int... transportTypes) {
super(dao);
Preconditions.checkArgument(transportTypes.length > 0);
routes = new HashSet<>();
routes.addAll(Collections2.filter(dao.getAllRoutes(),
new Predicate<Route>() {
List<Integer> list = Ints.asList(transportTypes);
@Override
public boolean apply(Route input) {
return list.contains(input.getType());
}
}));
LOG.info("Filtered down from {} to {} routes", input.getAllRoutes()
.size(), routes.size());
trips = Collections2.filter(super.getAllTrips(),
new TripByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} trips", super.getAllTrips()
.size(), trips.size());
stoptimes = Collections2.filter(super.getAllStopTimes(),
new StopTimeByRoutesPredicate(routes));
LOG.info("Filtered down from {} to {} stoptimes", input
.getAllStopTimes().size(), stoptimes.size());
stops = new HashSet<>();
stops.addAll(Collections2.transform(stoptimes,
new StopTimeToStopFunction()));
LOG.info("Filtered down from {} to {} stops", input.getAllStops()
.size(), stops.size());
serviceIds = new HashSet<>();
serviceIds.addAll(Collections2.transform(trips,
new TripToServiceIdFunction()));
LOG.info("Filtered down to {} serviceIds", serviceIds.size());
shapeIds = new HashSet<>();
shapeIds.addAll(Collections2.transform(trips,
new TripToShapeIdFunction()));
LOG.info("Filtered down to {} shapeIds", shapeIds.size());
}
|
diff --git a/src/java/org/apache/cassandra/hadoop/ColumnFamilyRecordReader.java b/src/java/org/apache/cassandra/hadoop/ColumnFamilyRecordReader.java
index d5786b528..afbda7f59 100644
--- a/src/java/org/apache/cassandra/hadoop/ColumnFamilyRecordReader.java
+++ b/src/java/org/apache/cassandra/hadoop/ColumnFamilyRecordReader.java
@@ -1,555 +1,558 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.hadoop;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.*;
import com.google.common.collect.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
public class ColumnFamilyRecordReader extends RecordReader<ByteBuffer, SortedMap<ByteBuffer, IColumn>>
implements org.apache.hadoop.mapred.RecordReader<ByteBuffer, SortedMap<ByteBuffer, IColumn>>
{
private static final Logger logger = LoggerFactory.getLogger(ColumnFamilyRecordReader.class);
public static final int CASSANDRA_HADOOP_MAX_KEY_SIZE_DEFAULT = 8192;
private ColumnFamilySplit split;
private RowIterator iter;
private Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>> currentRow;
private SlicePredicate predicate;
private boolean isEmptyPredicate;
private int totalRowCount; // total number of rows to fetch
private int batchSize; // fetch this many per batch
private String cfName;
private String keyspace;
private TSocket socket;
private Cassandra.Client client;
private ConsistencyLevel consistencyLevel;
private int keyBufferSize = 8192;
private List<IndexExpression> filter;
public ColumnFamilyRecordReader()
{
this(ColumnFamilyRecordReader.CASSANDRA_HADOOP_MAX_KEY_SIZE_DEFAULT);
}
public ColumnFamilyRecordReader(int keyBufferSize)
{
super();
this.keyBufferSize = keyBufferSize;
}
public void close()
{
if (socket != null && socket.isOpen())
{
socket.close();
socket = null;
client = null;
}
}
public ByteBuffer getCurrentKey()
{
return currentRow.left;
}
public SortedMap<ByteBuffer, IColumn> getCurrentValue()
{
return currentRow.right;
}
public float getProgress()
{
// TODO this is totally broken for wide rows
// the progress is likely to be reported slightly off the actual but close enough
float progress = ((float) iter.rowsRead() / totalRowCount);
return progress > 1.0F ? 1.0F : progress;
}
static boolean isEmptyPredicate(SlicePredicate predicate)
{
if (predicate == null)
return true;
if (predicate.isSetColumn_names() && predicate.getSlice_range() == null)
return false;
if (predicate.getSlice_range() == null)
return true;
byte[] start = predicate.getSlice_range().getStart();
if ((start != null) && (start.length > 0))
return false;
byte[] finish = predicate.getSlice_range().getFinish();
if ((finish != null) && (finish.length > 0))
return false;
return true;
}
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException
{
this.split = (ColumnFamilySplit) split;
Configuration conf = context.getConfiguration();
KeyRange jobRange = ConfigHelper.getInputKeyRange(conf);
filter = jobRange == null ? null : jobRange.row_filter;
predicate = ConfigHelper.getInputSlicePredicate(conf);
boolean widerows = ConfigHelper.getInputIsWide(conf);
isEmptyPredicate = isEmptyPredicate(predicate);
totalRowCount = ConfigHelper.getInputSplitSize(conf);
batchSize = ConfigHelper.getRangeBatchSize(conf);
cfName = ConfigHelper.getInputColumnFamily(conf);
consistencyLevel = ConsistencyLevel.valueOf(ConfigHelper.getReadConsistencyLevel(conf));
keyspace = ConfigHelper.getInputKeyspace(conf);
try
{
// only need to connect once
if (socket != null && socket.isOpen())
return;
// create connection using thrift
String location = getLocation();
socket = new TSocket(location, ConfigHelper.getInputRpcPort(conf));
TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TFramedTransport(socket));
client = new Cassandra.Client(binaryProtocol);
socket.open();
// log in
client.set_keyspace(keyspace);
if (ConfigHelper.getInputKeyspaceUserName(conf) != null)
{
Map<String, String> creds = new HashMap<String, String>();
creds.put(IAuthenticator.USERNAME_KEY, ConfigHelper.getInputKeyspaceUserName(conf));
creds.put(IAuthenticator.PASSWORD_KEY, ConfigHelper.getInputKeyspacePassword(conf));
AuthenticationRequest authRequest = new AuthenticationRequest(creds);
client.login(authRequest);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
iter = widerows ? new WideRowIterator() : new StaticRowIterator();
logger.debug("created {}", iter);
}
public boolean nextKeyValue() throws IOException
{
if (!iter.hasNext())
return false;
currentRow = iter.next();
return true;
}
// we don't use endpointsnitch since we are trying to support hadoop nodes that are
// not necessarily on Cassandra machines, too. This should be adequate for single-DC clusters, at least.
private String getLocation()
{
ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
try
{
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
while (nets.hasMoreElements())
localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses()));
}
catch (SocketException e)
{
throw new AssertionError(e);
}
for (InetAddress address : localAddresses)
{
for (String location : split.getLocations())
{
InetAddress locationAddress = null;
try
{
locationAddress = InetAddress.getByName(location);
}
catch (UnknownHostException e)
{
throw new AssertionError(e);
}
if (address.equals(locationAddress))
{
return location;
}
}
}
return split.getLocations()[0];
}
private abstract class RowIterator extends AbstractIterator<Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>>>
{
protected List<KeySlice> rows;
protected int totalRead = 0;
protected final AbstractType<?> comparator;
protected final AbstractType<?> subComparator;
protected final IPartitioner partitioner;
private RowIterator()
{
try
{
partitioner = FBUtilities.newPartitioner(client.describe_partitioner());
// Get the Keyspace metadata, then get the specific CF metadata
// in order to populate the sub/comparator.
KsDef ks_def = client.describe_keyspace(keyspace);
List<String> cfnames = new ArrayList<String>();
for (CfDef cfd : ks_def.cf_defs)
cfnames.add(cfd.name);
int idx = cfnames.indexOf(cfName);
CfDef cf_def = ks_def.cf_defs.get(idx);
comparator = TypeParser.parse(cf_def.comparator_type);
subComparator = cf_def.subcomparator_type == null ? null : TypeParser.parse(cf_def.subcomparator_type);
}
catch (ConfigurationException e)
{
throw new RuntimeException("unable to load sub/comparator", e);
}
catch (TException e)
{
throw new RuntimeException("error communicating via Thrift", e);
}
catch (Exception e)
{
throw new RuntimeException("unable to load keyspace " + keyspace, e);
}
}
/**
* @return total number of rows read by this record reader
*/
public int rowsRead()
{
return totalRead;
}
protected IColumn unthriftify(ColumnOrSuperColumn cosc)
{
if (cosc.counter_column != null)
return unthriftifyCounter(cosc.counter_column);
if (cosc.counter_super_column != null)
return unthriftifySuperCounter(cosc.counter_super_column);
if (cosc.super_column != null)
return unthriftifySuper(cosc.super_column);
assert cosc.column != null;
return unthriftifySimple(cosc.column);
}
private IColumn unthriftifySuper(SuperColumn super_column)
{
org.apache.cassandra.db.SuperColumn sc = new org.apache.cassandra.db.SuperColumn(super_column.name, subComparator);
for (Column column : super_column.columns)
{
sc.addColumn(unthriftifySimple(column));
}
return sc;
}
protected IColumn unthriftifySimple(Column column)
{
return new org.apache.cassandra.db.Column(column.name, column.value, column.timestamp);
}
private IColumn unthriftifyCounter(CounterColumn column)
{
//CounterColumns read the nodeID from the System table, so need the StorageService running and access
//to cassandra.yaml. To avoid a Hadoop needing access to yaml return a regular Column.
return new org.apache.cassandra.db.Column(column.name, ByteBufferUtil.bytes(column.value), 0);
}
private IColumn unthriftifySuperCounter(CounterSuperColumn superColumn)
{
org.apache.cassandra.db.SuperColumn sc = new org.apache.cassandra.db.SuperColumn(superColumn.name, subComparator);
for (CounterColumn column : superColumn.columns)
sc.addColumn(unthriftifyCounter(column));
return sc;
}
}
private class StaticRowIterator extends RowIterator
{
protected int i = 0;
private void maybeInit()
{
// check if we need another batch
if (rows != null && i < rows.size())
return;
String startToken;
if (totalRead == 0)
{
// first request
startToken = split.getStartToken();
}
else
{
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(Iterables.getLast(rows).key));
if (startToken.equals(split.getEndToken()))
{
// reached end of the split
rows = null;
return;
}
}
KeyRange keyRange = new KeyRange(batchSize)
.setStart_token(startToken)
.setEnd_token(split.getEndToken())
.setRow_filter(filter);
try
{
rows = client.get_range_slices(new ColumnParent(cfName), predicate, keyRange, consistencyLevel);
// nothing new? reached the end
if (rows.isEmpty())
{
rows = null;
return;
}
// prepare for the next slice to be read
KeySlice lastRow = rows.get(rows.size() - 1);
ByteBuffer rowkey = lastRow.key;
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(rowkey));
// remove ghosts when fetching all columns
if (isEmptyPredicate)
{
Iterator<KeySlice> it = rows.iterator();
- while (it.hasNext())
+ KeySlice ks;
+ do
{
- KeySlice ks = it.next();
+ ks = it.next();
if (ks.getColumnsSize() == 0)
{
it.remove();
}
- }
+ } while (it.hasNext());
// all ghosts, spooky
if (rows.isEmpty())
{
+ // maybeInit assumes it can get the start-with key from the rows collection, so add back the last
+ rows.add(ks);
maybeInit();
return;
}
}
// reset to iterate through this new batch
i = 0;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
protected Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>> computeNext()
{
maybeInit();
if (rows == null)
return endOfData();
totalRead++;
KeySlice ks = rows.get(i++);
SortedMap<ByteBuffer, IColumn> map = new TreeMap<ByteBuffer, IColumn>(comparator);
for (ColumnOrSuperColumn cosc : ks.columns)
{
IColumn column = unthriftify(cosc);
map.put(column.name(), column);
}
return new Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>>(ks.key, map);
}
}
private class WideRowIterator extends RowIterator
{
private PeekingIterator<Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>>> wideColumns;
private ByteBuffer lastColumn = ByteBufferUtil.EMPTY_BYTE_BUFFER;
private void maybeInit()
{
if (wideColumns != null && wideColumns.hasNext())
return;
KeyRange keyRange;
ByteBuffer startColumn;
if (totalRead == 0)
{
String startToken = split.getStartToken();
keyRange = new KeyRange(batchSize)
.setStart_token(startToken)
.setEnd_token(split.getEndToken())
.setRow_filter(filter);
}
else
{
KeySlice lastRow = Iterables.getLast(rows);
logger.debug("Starting with last-seen row {}", lastRow.key);
keyRange = new KeyRange(batchSize)
.setStart_key(lastRow.key)
.setEnd_token(split.getEndToken())
.setRow_filter(filter);
}
try
{
rows = client.get_paged_slice(cfName, keyRange, lastColumn, consistencyLevel);
int n = 0;
for (KeySlice row : rows)
n += row.columns.size();
logger.debug("read {} columns in {} rows for {} starting with {}",
new Object[]{ n, rows.size(), keyRange, lastColumn });
wideColumns = Iterators.peekingIterator(new WideColumnIterator(rows));
if (wideColumns.hasNext() && wideColumns.peek().right.keySet().iterator().next().equals(lastColumn))
wideColumns.next();
if (!wideColumns.hasNext())
rows = null;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
protected Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>> computeNext()
{
maybeInit();
if (rows == null)
return endOfData();
totalRead++;
Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>> next = wideColumns.next();
lastColumn = next.right.values().iterator().next().name();
return next;
}
private class WideColumnIterator extends AbstractIterator<Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>>>
{
private final Iterator<KeySlice> rows;
private Iterator<ColumnOrSuperColumn> columns;
public KeySlice currentRow;
public WideColumnIterator(List<KeySlice> rows)
{
this.rows = rows.iterator();
if (this.rows.hasNext())
nextRow();
else
columns = Iterators.emptyIterator();
}
private void nextRow()
{
currentRow = rows.next();
columns = currentRow.columns.iterator();
}
protected Pair<ByteBuffer, SortedMap<ByteBuffer, IColumn>> computeNext()
{
while (true)
{
if (columns.hasNext())
{
ColumnOrSuperColumn cosc = columns.next();
IColumn column = unthriftify(cosc);
ImmutableSortedMap<ByteBuffer, IColumn> map = ImmutableSortedMap.of(column.name(), column);
return Pair.<ByteBuffer, SortedMap<ByteBuffer, IColumn>>create(currentRow.key, map);
}
if (!rows.hasNext())
return endOfData();
nextRow();
}
}
}
}
// Because the old Hadoop API wants us to write to the key and value
// and the new asks for them, we need to copy the output of the new API
// to the old. Thus, expect a small performance hit.
// And obviously this wouldn't work for wide rows. But since ColumnFamilyInputFormat
// and ColumnFamilyRecordReader don't support them, it should be fine for now.
public boolean next(ByteBuffer key, SortedMap<ByteBuffer, IColumn> value) throws IOException
{
if (this.nextKeyValue())
{
key.clear();
key.put(this.getCurrentKey());
key.rewind();
value.clear();
value.putAll(this.getCurrentValue());
return true;
}
return false;
}
public ByteBuffer createKey()
{
return ByteBuffer.wrap(new byte[this.keyBufferSize]);
}
public SortedMap<ByteBuffer, IColumn> createValue()
{
return new TreeMap<ByteBuffer, IColumn>();
}
public long getPos() throws IOException
{
return (long)iter.rowsRead();
}
}
| false | true | private void maybeInit()
{
// check if we need another batch
if (rows != null && i < rows.size())
return;
String startToken;
if (totalRead == 0)
{
// first request
startToken = split.getStartToken();
}
else
{
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(Iterables.getLast(rows).key));
if (startToken.equals(split.getEndToken()))
{
// reached end of the split
rows = null;
return;
}
}
KeyRange keyRange = new KeyRange(batchSize)
.setStart_token(startToken)
.setEnd_token(split.getEndToken())
.setRow_filter(filter);
try
{
rows = client.get_range_slices(new ColumnParent(cfName), predicate, keyRange, consistencyLevel);
// nothing new? reached the end
if (rows.isEmpty())
{
rows = null;
return;
}
// prepare for the next slice to be read
KeySlice lastRow = rows.get(rows.size() - 1);
ByteBuffer rowkey = lastRow.key;
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(rowkey));
// remove ghosts when fetching all columns
if (isEmptyPredicate)
{
Iterator<KeySlice> it = rows.iterator();
while (it.hasNext())
{
KeySlice ks = it.next();
if (ks.getColumnsSize() == 0)
{
it.remove();
}
}
// all ghosts, spooky
if (rows.isEmpty())
{
maybeInit();
return;
}
}
// reset to iterate through this new batch
i = 0;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
| private void maybeInit()
{
// check if we need another batch
if (rows != null && i < rows.size())
return;
String startToken;
if (totalRead == 0)
{
// first request
startToken = split.getStartToken();
}
else
{
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(Iterables.getLast(rows).key));
if (startToken.equals(split.getEndToken()))
{
// reached end of the split
rows = null;
return;
}
}
KeyRange keyRange = new KeyRange(batchSize)
.setStart_token(startToken)
.setEnd_token(split.getEndToken())
.setRow_filter(filter);
try
{
rows = client.get_range_slices(new ColumnParent(cfName), predicate, keyRange, consistencyLevel);
// nothing new? reached the end
if (rows.isEmpty())
{
rows = null;
return;
}
// prepare for the next slice to be read
KeySlice lastRow = rows.get(rows.size() - 1);
ByteBuffer rowkey = lastRow.key;
startToken = partitioner.getTokenFactory().toString(partitioner.getToken(rowkey));
// remove ghosts when fetching all columns
if (isEmptyPredicate)
{
Iterator<KeySlice> it = rows.iterator();
KeySlice ks;
do
{
ks = it.next();
if (ks.getColumnsSize() == 0)
{
it.remove();
}
} while (it.hasNext());
// all ghosts, spooky
if (rows.isEmpty())
{
// maybeInit assumes it can get the start-with key from the rows collection, so add back the last
rows.add(ks);
maybeInit();
return;
}
}
// reset to iterate through this new batch
i = 0;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
|
diff --git a/src/main/java/org/apache/commons/ognl/NumericExpression.java b/src/main/java/org/apache/commons/ognl/NumericExpression.java
index ca96113..8f7fa9d 100644
--- a/src/main/java/org/apache/commons/ognl/NumericExpression.java
+++ b/src/main/java/org/apache/commons/ognl/NumericExpression.java
@@ -1,141 +1,143 @@
package org.apache.commons.ognl;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
/**
* Base class for numeric expressions.
*/
public abstract class NumericExpression
extends ExpressionNode
implements NodeType
{
private static final long serialVersionUID = -174952564587478850L;
protected Class<?> _getterClass;
public NumericExpression( int id )
{
super( id );
}
public NumericExpression( OgnlParser p, int id )
{
super( p, id );
}
/**
* {@inheritDoc}
*/
public Class<?> getGetterClass()
{
if ( _getterClass != null )
return _getterClass;
return Double.TYPE;
}
/**
* {@inheritDoc}
*/
public Class<?> getSetterClass()
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String toGetSourceString( OgnlContext context, Object target )
{
Object value = null;
StringBuilder result = new StringBuilder( "" );
try
{
value = getValueBody( context, target );
if ( value != null )
_getterClass = value.getClass();
for ( int i = 0; i < _children.length; i++ )
{
if ( i > 0 )
result.append( " " ).append( getExpressionOperator( i ) ).append( " " );
String str = OgnlRuntime.getChildSource( context, target, _children[i] );
result.append( coerceToNumeric( str, context, _children[i] ) );
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result.toString();
}
public String coerceToNumeric( String source, OgnlContext context, Node child )
{
StringBuilder ret = new StringBuilder( source );
Object value = context.getCurrentObject();
if ( ASTConst.class.isInstance( child ) && value != null )
{
return value.toString();
}
if ( context.getCurrentType() != null && !context.getCurrentType().isPrimitive()
&& context.getCurrentObject() != null && Number.class.isInstance( context.getCurrentObject() ) )
{
- ret.append( "((")
+ ret = new StringBuilder( "((")
.append( ExpressionCompiler.getCastString( context.getCurrentObject().getClass() ))
.append( ")")
.append( ret)
.append( ").")
.append( OgnlRuntime.getNumericValueGetter( context.getCurrentObject().getClass() ) );
}
else if ( context.getCurrentType() != null && context.getCurrentType().isPrimitive()
&& ( ASTConst.class.isInstance( child ) || NumericExpression.class.isInstance( child ) ) )
{
@SuppressWarnings( "unchecked" ) // checked by the condition in the if clause
Class<? extends Number> numberClass = (Class<? extends Number>) context.getCurrentType();
ret.append( OgnlRuntime.getNumericLiteral( numberClass ) );
}
else if ( context.getCurrentType() != null && String.class.isAssignableFrom( context.getCurrentType() ) )
{
- ret.append( "Double.parseDouble(").append( ")" );
+ ret = new StringBuilder( "Double.parseDouble(")
+ .append( ret.toString() )
+ .append( ")" );
context.setCurrentType( Double.TYPE );
}
if ( NumericExpression.class.isInstance( child ) )
{
- ret.append( "(" ).append( ret ).append( ")" );
+ ret = new StringBuilder( "(" ).append( ret ).append( ")" );
}
return ret.toString();
}
}
| false | true | public String coerceToNumeric( String source, OgnlContext context, Node child )
{
StringBuilder ret = new StringBuilder( source );
Object value = context.getCurrentObject();
if ( ASTConst.class.isInstance( child ) && value != null )
{
return value.toString();
}
if ( context.getCurrentType() != null && !context.getCurrentType().isPrimitive()
&& context.getCurrentObject() != null && Number.class.isInstance( context.getCurrentObject() ) )
{
ret.append( "((")
.append( ExpressionCompiler.getCastString( context.getCurrentObject().getClass() ))
.append( ")")
.append( ret)
.append( ").")
.append( OgnlRuntime.getNumericValueGetter( context.getCurrentObject().getClass() ) );
}
else if ( context.getCurrentType() != null && context.getCurrentType().isPrimitive()
&& ( ASTConst.class.isInstance( child ) || NumericExpression.class.isInstance( child ) ) )
{
@SuppressWarnings( "unchecked" ) // checked by the condition in the if clause
Class<? extends Number> numberClass = (Class<? extends Number>) context.getCurrentType();
ret.append( OgnlRuntime.getNumericLiteral( numberClass ) );
}
else if ( context.getCurrentType() != null && String.class.isAssignableFrom( context.getCurrentType() ) )
{
ret.append( "Double.parseDouble(").append( ")" );
context.setCurrentType( Double.TYPE );
}
if ( NumericExpression.class.isInstance( child ) )
{
ret.append( "(" ).append( ret ).append( ")" );
}
return ret.toString();
}
| public String coerceToNumeric( String source, OgnlContext context, Node child )
{
StringBuilder ret = new StringBuilder( source );
Object value = context.getCurrentObject();
if ( ASTConst.class.isInstance( child ) && value != null )
{
return value.toString();
}
if ( context.getCurrentType() != null && !context.getCurrentType().isPrimitive()
&& context.getCurrentObject() != null && Number.class.isInstance( context.getCurrentObject() ) )
{
ret = new StringBuilder( "((")
.append( ExpressionCompiler.getCastString( context.getCurrentObject().getClass() ))
.append( ")")
.append( ret)
.append( ").")
.append( OgnlRuntime.getNumericValueGetter( context.getCurrentObject().getClass() ) );
}
else if ( context.getCurrentType() != null && context.getCurrentType().isPrimitive()
&& ( ASTConst.class.isInstance( child ) || NumericExpression.class.isInstance( child ) ) )
{
@SuppressWarnings( "unchecked" ) // checked by the condition in the if clause
Class<? extends Number> numberClass = (Class<? extends Number>) context.getCurrentType();
ret.append( OgnlRuntime.getNumericLiteral( numberClass ) );
}
else if ( context.getCurrentType() != null && String.class.isAssignableFrom( context.getCurrentType() ) )
{
ret = new StringBuilder( "Double.parseDouble(")
.append( ret.toString() )
.append( ")" );
context.setCurrentType( Double.TYPE );
}
if ( NumericExpression.class.isInstance( child ) )
{
ret = new StringBuilder( "(" ).append( ret ).append( ")" );
}
return ret.toString();
}
|
diff --git a/src/com/eteks/sweethome3d/swing/JPEGImagesToVideo.java b/src/com/eteks/sweethome3d/swing/JPEGImagesToVideo.java
index 938a33d5..75ff3fdf 100644
--- a/src/com/eteks/sweethome3d/swing/JPEGImagesToVideo.java
+++ b/src/com/eteks/sweethome3d/swing/JPEGImagesToVideo.java
@@ -1,208 +1,209 @@
/*
* JPEGImagesToVideo.java
*
* From http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/solutions/JpegImagesToMovie.java 1.3 01/03/13
*
* Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear facility.
* Licensee represents and warrants that it will not use or redistribute the
* Software for such purposes.
*/
package com.eteks.sweethome3d.swing;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import javax.media.ConfigureCompleteEvent;
import javax.media.Controller;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.DataSink;
import javax.media.EndOfMediaEvent;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoDataSinkException;
import javax.media.NoProcessorException;
import javax.media.PrefetchCompleteEvent;
import javax.media.Processor;
import javax.media.RealizeCompleteEvent;
import javax.media.ResourceUnavailableEvent;
import javax.media.control.TrackControl;
import javax.media.datasink.DataSinkErrorEvent;
import javax.media.datasink.DataSinkEvent;
import javax.media.datasink.DataSinkListener;
import javax.media.datasink.EndOfStreamEvent;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;
import javax.media.protocol.FileTypeDescriptor;
/**
* This program takes a list of images and convert them into a
* QuickTime movie.
*/
public class JPEGImagesToVideo {
private Object waitSync;
private boolean stateTransitionOK;
private Object waitFileSync;
private boolean fileDone;
private String fileError;
/**
* Creates a video file at the given size and frame rate.
*/
public void createVideoFile(int width, int height, int frameRate, DataSource dataSource, File file) throws IOException {
this.waitSync = new Object();
this.stateTransitionOK = true;
this.waitFileSync = new Object();
this.fileDone = false;
this.fileError = null;
ControllerListener controllerListener = new ControllerListener() {
public void controllerUpdate(ControllerEvent ev) {
if (ev instanceof ConfigureCompleteEvent
|| ev instanceof RealizeCompleteEvent
|| ev instanceof PrefetchCompleteEvent) {
synchronized (waitSync) {
stateTransitionOK = true;
waitSync.notifyAll();
}
} else if (ev instanceof ResourceUnavailableEvent) {
synchronized (waitSync) {
stateTransitionOK = false;
waitSync.notifyAll();
}
} else if (ev instanceof EndOfMediaEvent) {
ev.getSourceController().stop();
ev.getSourceController().close();
}
}
};
DataSinkListener dataSinkListener = new DataSinkListener() {
public void dataSinkUpdate(DataSinkEvent ev) {
if (ev instanceof EndOfStreamEvent) {
synchronized (waitFileSync) {
fileDone = true;
waitFileSync.notifyAll();
}
} else if (ev instanceof DataSinkErrorEvent) {
synchronized (waitFileSync) {
fileDone = true;
fileError = "Data sink error";
waitFileSync.notifyAll();
}
}
}
};
Processor processor = null;
DataSink dataSink = null;
try {
processor = Manager.createProcessor(dataSource);
processor.addControllerListener(controllerListener);
processor.configure();
// Put the Processor into configured state so we can set
// some processing options on the processor.
if (!waitForState(processor, Processor.Configured)) {
throw new IOException("Failed to configure the processor.");
}
// Set the output content descriptor to QuickTime.
processor.setContentDescriptor(new ContentDescriptor(FileTypeDescriptor.QUICKTIME));
// Query for the processor for supported formats.
// Then set it on the processor.
TrackControl trackControls[] = processor.getTrackControls();
Format format[] = trackControls [0].getSupportedFormats();
if (format == null || format.length <= 0) {
throw new IOException("The mux does not support the input format: " + trackControls [0].getFormat());
}
trackControls [0].setFormat(format [0]);
// We are done with programming the processor. Let's just realize it.
processor.realize();
if (!waitForState(processor, Controller.Realized)) {
throw new IOException("Failed to realize the processor.");
}
// Now, we'll need to create a DataSink.
+ // Caution: do not use file.toURI().toURL() with JMF
dataSink = Manager.createDataSink(processor.getDataOutput(),
- new MediaLocator(file.toURI().toURL()));
+ new MediaLocator(file.toURL()));
dataSink.open();
dataSink.addDataSinkListener(dataSinkListener);
this.fileDone = false;
// Start the actual transcoding
processor.start();
dataSink.start();
// Wait for EndOfStream event.
synchronized (this.waitFileSync) {
while (!this.fileDone) {
this.waitFileSync.wait();
}
}
if (this.fileError != null) {
throw new IOException(this.fileError);
}
} catch (NoProcessorException ex) {
IOException ex2 = new IOException(ex.getMessage());
ex2.initCause(ex);
throw ex2;
} catch (NoDataSinkException ex) {
IOException ex2 = new IOException("Failed to create a DataSink for the given output MediaLocator");
ex2.initCause(ex);
throw ex2;
} catch (InterruptedException ex) {
if (dataSink != null) {
dataSink.stop();
}
throw new InterruptedIOException("Video creation interrupted");
} finally {
if (dataSink != null) {
dataSink.close();
dataSink.removeDataSinkListener(dataSinkListener);
}
if (processor != null) {
processor.close();
processor.removeControllerListener(controllerListener);
}
}
}
/**
* Blocks until the processor has transitioned to the given state. Return false
* if the transition failed.
*/
private boolean waitForState(Processor p, int state) throws InterruptedException {
synchronized (waitSync) {
while (p.getState() < state && stateTransitionOK) {
waitSync.wait();
}
}
return stateTransitionOK;
}
}
| false | true | public void createVideoFile(int width, int height, int frameRate, DataSource dataSource, File file) throws IOException {
this.waitSync = new Object();
this.stateTransitionOK = true;
this.waitFileSync = new Object();
this.fileDone = false;
this.fileError = null;
ControllerListener controllerListener = new ControllerListener() {
public void controllerUpdate(ControllerEvent ev) {
if (ev instanceof ConfigureCompleteEvent
|| ev instanceof RealizeCompleteEvent
|| ev instanceof PrefetchCompleteEvent) {
synchronized (waitSync) {
stateTransitionOK = true;
waitSync.notifyAll();
}
} else if (ev instanceof ResourceUnavailableEvent) {
synchronized (waitSync) {
stateTransitionOK = false;
waitSync.notifyAll();
}
} else if (ev instanceof EndOfMediaEvent) {
ev.getSourceController().stop();
ev.getSourceController().close();
}
}
};
DataSinkListener dataSinkListener = new DataSinkListener() {
public void dataSinkUpdate(DataSinkEvent ev) {
if (ev instanceof EndOfStreamEvent) {
synchronized (waitFileSync) {
fileDone = true;
waitFileSync.notifyAll();
}
} else if (ev instanceof DataSinkErrorEvent) {
synchronized (waitFileSync) {
fileDone = true;
fileError = "Data sink error";
waitFileSync.notifyAll();
}
}
}
};
Processor processor = null;
DataSink dataSink = null;
try {
processor = Manager.createProcessor(dataSource);
processor.addControllerListener(controllerListener);
processor.configure();
// Put the Processor into configured state so we can set
// some processing options on the processor.
if (!waitForState(processor, Processor.Configured)) {
throw new IOException("Failed to configure the processor.");
}
// Set the output content descriptor to QuickTime.
processor.setContentDescriptor(new ContentDescriptor(FileTypeDescriptor.QUICKTIME));
// Query for the processor for supported formats.
// Then set it on the processor.
TrackControl trackControls[] = processor.getTrackControls();
Format format[] = trackControls [0].getSupportedFormats();
if (format == null || format.length <= 0) {
throw new IOException("The mux does not support the input format: " + trackControls [0].getFormat());
}
trackControls [0].setFormat(format [0]);
// We are done with programming the processor. Let's just realize it.
processor.realize();
if (!waitForState(processor, Controller.Realized)) {
throw new IOException("Failed to realize the processor.");
}
// Now, we'll need to create a DataSink.
dataSink = Manager.createDataSink(processor.getDataOutput(),
new MediaLocator(file.toURI().toURL()));
dataSink.open();
dataSink.addDataSinkListener(dataSinkListener);
this.fileDone = false;
// Start the actual transcoding
processor.start();
dataSink.start();
// Wait for EndOfStream event.
synchronized (this.waitFileSync) {
while (!this.fileDone) {
this.waitFileSync.wait();
}
}
if (this.fileError != null) {
throw new IOException(this.fileError);
}
} catch (NoProcessorException ex) {
IOException ex2 = new IOException(ex.getMessage());
ex2.initCause(ex);
throw ex2;
} catch (NoDataSinkException ex) {
IOException ex2 = new IOException("Failed to create a DataSink for the given output MediaLocator");
ex2.initCause(ex);
throw ex2;
} catch (InterruptedException ex) {
if (dataSink != null) {
dataSink.stop();
}
throw new InterruptedIOException("Video creation interrupted");
} finally {
if (dataSink != null) {
dataSink.close();
dataSink.removeDataSinkListener(dataSinkListener);
}
if (processor != null) {
processor.close();
processor.removeControllerListener(controllerListener);
}
}
}
| public void createVideoFile(int width, int height, int frameRate, DataSource dataSource, File file) throws IOException {
this.waitSync = new Object();
this.stateTransitionOK = true;
this.waitFileSync = new Object();
this.fileDone = false;
this.fileError = null;
ControllerListener controllerListener = new ControllerListener() {
public void controllerUpdate(ControllerEvent ev) {
if (ev instanceof ConfigureCompleteEvent
|| ev instanceof RealizeCompleteEvent
|| ev instanceof PrefetchCompleteEvent) {
synchronized (waitSync) {
stateTransitionOK = true;
waitSync.notifyAll();
}
} else if (ev instanceof ResourceUnavailableEvent) {
synchronized (waitSync) {
stateTransitionOK = false;
waitSync.notifyAll();
}
} else if (ev instanceof EndOfMediaEvent) {
ev.getSourceController().stop();
ev.getSourceController().close();
}
}
};
DataSinkListener dataSinkListener = new DataSinkListener() {
public void dataSinkUpdate(DataSinkEvent ev) {
if (ev instanceof EndOfStreamEvent) {
synchronized (waitFileSync) {
fileDone = true;
waitFileSync.notifyAll();
}
} else if (ev instanceof DataSinkErrorEvent) {
synchronized (waitFileSync) {
fileDone = true;
fileError = "Data sink error";
waitFileSync.notifyAll();
}
}
}
};
Processor processor = null;
DataSink dataSink = null;
try {
processor = Manager.createProcessor(dataSource);
processor.addControllerListener(controllerListener);
processor.configure();
// Put the Processor into configured state so we can set
// some processing options on the processor.
if (!waitForState(processor, Processor.Configured)) {
throw new IOException("Failed to configure the processor.");
}
// Set the output content descriptor to QuickTime.
processor.setContentDescriptor(new ContentDescriptor(FileTypeDescriptor.QUICKTIME));
// Query for the processor for supported formats.
// Then set it on the processor.
TrackControl trackControls[] = processor.getTrackControls();
Format format[] = trackControls [0].getSupportedFormats();
if (format == null || format.length <= 0) {
throw new IOException("The mux does not support the input format: " + trackControls [0].getFormat());
}
trackControls [0].setFormat(format [0]);
// We are done with programming the processor. Let's just realize it.
processor.realize();
if (!waitForState(processor, Controller.Realized)) {
throw new IOException("Failed to realize the processor.");
}
// Now, we'll need to create a DataSink.
// Caution: do not use file.toURI().toURL() with JMF
dataSink = Manager.createDataSink(processor.getDataOutput(),
new MediaLocator(file.toURL()));
dataSink.open();
dataSink.addDataSinkListener(dataSinkListener);
this.fileDone = false;
// Start the actual transcoding
processor.start();
dataSink.start();
// Wait for EndOfStream event.
synchronized (this.waitFileSync) {
while (!this.fileDone) {
this.waitFileSync.wait();
}
}
if (this.fileError != null) {
throw new IOException(this.fileError);
}
} catch (NoProcessorException ex) {
IOException ex2 = new IOException(ex.getMessage());
ex2.initCause(ex);
throw ex2;
} catch (NoDataSinkException ex) {
IOException ex2 = new IOException("Failed to create a DataSink for the given output MediaLocator");
ex2.initCause(ex);
throw ex2;
} catch (InterruptedException ex) {
if (dataSink != null) {
dataSink.stop();
}
throw new InterruptedIOException("Video creation interrupted");
} finally {
if (dataSink != null) {
dataSink.close();
dataSink.removeDataSinkListener(dataSinkListener);
}
if (processor != null) {
processor.close();
processor.removeControllerListener(controllerListener);
}
}
}
|
diff --git a/src/main/java/net/canarymod/api/factory/CanaryNBTFactory.java b/src/main/java/net/canarymod/api/factory/CanaryNBTFactory.java
index 269d70f..a7ae071 100644
--- a/src/main/java/net/canarymod/api/factory/CanaryNBTFactory.java
+++ b/src/main/java/net/canarymod/api/factory/CanaryNBTFactory.java
@@ -1,154 +1,154 @@
package net.canarymod.api.factory;
import net.canarymod.api.nbt.BaseTag;
import net.canarymod.api.nbt.ByteArrayTag;
import net.canarymod.api.nbt.ByteTag;
import net.canarymod.api.nbt.CanaryByteArrayTag;
import net.canarymod.api.nbt.CanaryByteTag;
import net.canarymod.api.nbt.CanaryCompoundTag;
import net.canarymod.api.nbt.CanaryDoubleTag;
import net.canarymod.api.nbt.CanaryFloatTag;
import net.canarymod.api.nbt.CanaryIntArrayTag;
import net.canarymod.api.nbt.CanaryIntTag;
import net.canarymod.api.nbt.CanaryListTag;
import net.canarymod.api.nbt.CanaryLongTag;
import net.canarymod.api.nbt.CanaryShortTag;
import net.canarymod.api.nbt.CanaryStringTag;
import net.canarymod.api.nbt.CompoundTag;
import net.canarymod.api.nbt.DoubleTag;
import net.canarymod.api.nbt.FloatTag;
import net.canarymod.api.nbt.IntArrayTag;
import net.canarymod.api.nbt.IntTag;
import net.canarymod.api.nbt.ListTag;
import net.canarymod.api.nbt.LongTag;
import net.canarymod.api.nbt.NBTTagType;
import net.canarymod.api.nbt.ShortTag;
import net.canarymod.api.nbt.StringTag;
public final class CanaryNBTFactory implements NBTFactory {
/**
* {@inheritDoc}
*/
@Override
public CompoundTag newCompoundTag(String name) {
return new CanaryCompoundTag(name);
}
/**
* {@inheritDoc}
*/
@Override
public ByteTag newByteTag(String name, byte value) {
return new CanaryByteTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public ByteArrayTag newByteArrayTag(String name, byte[] value) {
return new CanaryByteArrayTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public DoubleTag newDoubleTag(String name, double value) {
return new CanaryDoubleTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public FloatTag newFloatTag(String name, float value) {
return new CanaryFloatTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public IntTag newIntTag(String name, int value) {
return new CanaryIntTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public IntArrayTag newIntArrayTag(String name, int[] value) {
return new CanaryIntArrayTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public <E extends BaseTag> ListTag<E> newListTag(String name) {
return new CanaryListTag<E>(name);
}
/**
* {@inheritDoc}
*/
@Override
public LongTag newLongTag(String name, long value) {
return new CanaryLongTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public ShortTag newShortTag(String name, short value) {
return new CanaryShortTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public StringTag newStringTag(String name, String value) {
return new CanaryStringTag(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public BaseTag newTagFromType(NBTTagType type, String name, Object value) {
try {
switch (type) {
case BYTE:
return newByteTag(name, (Byte) value);
case BYTE_ARRAY:
return newByteArrayTag(name, (byte[]) value);
case COMPOUND:
return newCompoundTag(name);
case DOUBLE:
return newDoubleTag(name, (Double) value);
case FLOAT:
return newFloatTag(name, (Float) value);
case INT:
return newIntTag(name, (Integer) value);
case INT_ARRAY:
return newIntArrayTag(name, (int[]) value);
case LIST:
return newListTag(name);
case LONG:
return newLongTag(name, (Long) value);
case SHORT:
return newShortTag(name, (Short) value);
case STRING:
- return newStringTag(name, (String) value);
+ return newStringTag(name, value == null ? "null" : (String) value);
default:
return null;
}
} catch (Exception ex) {
return null;
}
}
}
| true | true | public BaseTag newTagFromType(NBTTagType type, String name, Object value) {
try {
switch (type) {
case BYTE:
return newByteTag(name, (Byte) value);
case BYTE_ARRAY:
return newByteArrayTag(name, (byte[]) value);
case COMPOUND:
return newCompoundTag(name);
case DOUBLE:
return newDoubleTag(name, (Double) value);
case FLOAT:
return newFloatTag(name, (Float) value);
case INT:
return newIntTag(name, (Integer) value);
case INT_ARRAY:
return newIntArrayTag(name, (int[]) value);
case LIST:
return newListTag(name);
case LONG:
return newLongTag(name, (Long) value);
case SHORT:
return newShortTag(name, (Short) value);
case STRING:
return newStringTag(name, (String) value);
default:
return null;
}
} catch (Exception ex) {
return null;
}
}
| public BaseTag newTagFromType(NBTTagType type, String name, Object value) {
try {
switch (type) {
case BYTE:
return newByteTag(name, (Byte) value);
case BYTE_ARRAY:
return newByteArrayTag(name, (byte[]) value);
case COMPOUND:
return newCompoundTag(name);
case DOUBLE:
return newDoubleTag(name, (Double) value);
case FLOAT:
return newFloatTag(name, (Float) value);
case INT:
return newIntTag(name, (Integer) value);
case INT_ARRAY:
return newIntArrayTag(name, (int[]) value);
case LIST:
return newListTag(name);
case LONG:
return newLongTag(name, (Long) value);
case SHORT:
return newShortTag(name, (Short) value);
case STRING:
return newStringTag(name, value == null ? "null" : (String) value);
default:
return null;
}
} catch (Exception ex) {
return null;
}
}
|
diff --git a/src/kg/apc/jmeter/config/VariablesFromCSVFile.java b/src/kg/apc/jmeter/config/VariablesFromCSVFile.java
index 0a8a7e75..632e86ea 100644
--- a/src/kg/apc/jmeter/config/VariablesFromCSVFile.java
+++ b/src/kg/apc/jmeter/config/VariablesFromCSVFile.java
@@ -1,165 +1,165 @@
package kg.apc.jmeter.config;
import java.io.IOException;
import org.apache.jmeter.config.CSVDataSet;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.engine.event.LoopIterationListener;
import org.apache.jmeter.engine.util.NoThreadClone;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testbeans.TestBean;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
/**
*
* @author apc
* @see CSVDataSet
*/
public class VariablesFromCSVFile
extends ConfigTestElement
implements TestBean,
LoopIterationListener,
NoThreadClone
{
private static final Logger log = LoggingManager.getLoggerForClass();
private String variablesPrefix;
private String delimiter;
private String filename;
/**
*
* @return
*/
public String getFilename()
{
return filename;
}
/**
*
* @param filename
*/
public void setFilename(String filename)
{
this.filename = filename;
}
/**
*
* @return
*/
public String getVariablesPrefix()
{
return variablesPrefix;
}
/**
*
* @param variableNames
*/
public void setVariablesPrefix(String variableNames)
{
this.variablesPrefix = variableNames;
}
/**
*
* @return
*/
public String getDelimiter()
{
return delimiter;
}
/**
*
* @param delimiter
*/
public void setDelimiter(String delimiter)
{
this.delimiter = delimiter;
}
public void iterationStart(LoopIterationEvent iterEvent)
{
int threanNo = JMeterContextService.getContext().getThreadNum();
// once only
if (iterEvent.getIteration() > 1)
{
log.debug("Variables already loaded for thread " + Integer.toString(threanNo));
return;
}
if (getFilename().length()==0)
{
return;
}
log.debug("Started loading variables from CSV for thread " + Integer.toString(threanNo));
JMeterVariables variables = JMeterContextService.getContext().getVariables();
- String alias = this.getClass().getName() + Integer.toString(threanNo);
+ String alias = this.getClass().getName() + getFilename() + Integer.toString(threanNo);
FileServer server = FileServer.getFileServer();
server.reserveFile(getFilename(), "UTF-8", alias);
String delim = getResultingDelimiter();
try
{
String line = null;
while ((line = server.readLine(alias, false)) != null)
{
processCSVFileLine(line, delim, variables);
}
server.closeFile(alias);
}
catch (IOException e)
{
log.error(e.toString());
}
log.debug("Finished loading variables from CSV for thread " + Integer.toString(threanNo));
}
private void processCSVFileLine(String line, String delim, JMeterVariables variables)
{
String[] lineValues = JOrphanUtils.split(line, delim, false);
//REV SH - Issue 3: Blank lines cause Java Exception
switch (lineValues.length) {
case 1:
log.warn("Less than 2 columns at line: " + line);
variables.put(getVariablesPrefix() + lineValues[0], "");
break;
case 2:
//log.info("Variable: " + getVariablesPrefix() + lineValues[0] + "=" + lineValues[1] + " was: " + variables.get(getVariablesPrefix() + lineValues[0]));
variables.put(getVariablesPrefix() + lineValues[0], lineValues[1]);
break;
default:
log.warn("Bad format for line: " + line);
break;
}
}
private String getResultingDelimiter()
{
String delim = delimiter;
if (delim.equals("\\t"))
{
delim = "\t";
}
else if (delim.length() == 0)
{
log.warn("Empty delimiter converted to ','");
delim = ",";
}
//log.debug("Delimiter: " + delim);
return delim;
}
}
| true | true | public void iterationStart(LoopIterationEvent iterEvent)
{
int threanNo = JMeterContextService.getContext().getThreadNum();
// once only
if (iterEvent.getIteration() > 1)
{
log.debug("Variables already loaded for thread " + Integer.toString(threanNo));
return;
}
if (getFilename().length()==0)
{
return;
}
log.debug("Started loading variables from CSV for thread " + Integer.toString(threanNo));
JMeterVariables variables = JMeterContextService.getContext().getVariables();
String alias = this.getClass().getName() + Integer.toString(threanNo);
FileServer server = FileServer.getFileServer();
server.reserveFile(getFilename(), "UTF-8", alias);
String delim = getResultingDelimiter();
try
{
String line = null;
while ((line = server.readLine(alias, false)) != null)
{
processCSVFileLine(line, delim, variables);
}
server.closeFile(alias);
}
catch (IOException e)
{
log.error(e.toString());
}
log.debug("Finished loading variables from CSV for thread " + Integer.toString(threanNo));
}
| public void iterationStart(LoopIterationEvent iterEvent)
{
int threanNo = JMeterContextService.getContext().getThreadNum();
// once only
if (iterEvent.getIteration() > 1)
{
log.debug("Variables already loaded for thread " + Integer.toString(threanNo));
return;
}
if (getFilename().length()==0)
{
return;
}
log.debug("Started loading variables from CSV for thread " + Integer.toString(threanNo));
JMeterVariables variables = JMeterContextService.getContext().getVariables();
String alias = this.getClass().getName() + getFilename() + Integer.toString(threanNo);
FileServer server = FileServer.getFileServer();
server.reserveFile(getFilename(), "UTF-8", alias);
String delim = getResultingDelimiter();
try
{
String line = null;
while ((line = server.readLine(alias, false)) != null)
{
processCSVFileLine(line, delim, variables);
}
server.closeFile(alias);
}
catch (IOException e)
{
log.error(e.toString());
}
log.debug("Finished loading variables from CSV for thread " + Integer.toString(threanNo));
}
|
diff --git a/tools/src/XJavac.java b/tools/src/XJavac.java
index 8d7d0bf47..a07569e83 100644
--- a/tools/src/XJavac.java
+++ b/tools/src/XJavac.java
@@ -1,156 +1,158 @@
/*
* 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.xerces.util;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.JavaEnvUtils;
import org.apache.tools.ant.taskdefs.Javac;
import java.lang.StringBuffer;
import java.util.Properties;
import java.util.Locale;
/**
* The implementation of the javac compiler for JDK 1.4 and above
*
* The purpose of this task is to diagnose whether we're
* running on a 1.4 or above JVM; if we are, to
* set up the bootclasspath such that the build will
* succeed; if we aren't, then invoke the Javac12
* task.
*
* @author Neil Graham, IBM
*/
public class XJavac extends Javac {
/**
* Run the compilation.
*
* @exception BuildException if the compilation has problems.
*/
public void execute() throws BuildException {
if(isJDK14OrHigher()) {
// maybe the right one; check vendor:
// by checking system properties:
Properties props = null;
try {
props = System.getProperties();
} catch (Exception e) {
throw new BuildException("unable to determine java vendor because could not access system properties!");
}
// this is supposed to be provided by all JVM's from time immemorial
String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH);
if (vendor.indexOf("IBM") >= 0) {
// we're on an IBM 1.4 or higher; fiddle with the bootclasspath.
setBootclasspath(createIBMJDKBootclasspath());
}
// need to do special things for Sun/Oracle too and also
// for Apple, HP, FreeBSD, SableVM, Kaffe and Blackdown: a Linux port of Sun Java
else if( (vendor.indexOf("SUN") >= 0) ||
(vendor.indexOf("ORACLE") >= 0) ||
(vendor.indexOf("BLACKDOWN") >= 0) ||
(vendor.indexOf("APPLE") >= 0) ||
(vendor.indexOf("HEWLETT-PACKARD") >= 0) ||
(vendor.indexOf("KAFFE") >= 0) ||
(vendor.indexOf("SABLE") >= 0) ||
(vendor.indexOf("FREEBSD") >= 0)) {
// we're on an SUN 1.4 or higher; fiddle with the bootclasspath.
// since we can't eviscerate XML-related info here,
// we must use the classpath
Path bcp = createBootclasspath();
Path clPath = getClasspath();
bcp.append(clPath);
String currBCP = (String)props.get("sun.boot.class.path");
Path currBCPath = new Path(null);
currBCPath.createPathElement().setPath(currBCP);
bcp.append(currBCPath);
setBootclasspath(bcp);
}
}
// now just do the normal thing:
super.execute();
}
/**
* Creates bootclasspath for IBM JDK 1.4 and above.
*/
private Path createIBMJDKBootclasspath() {
Path bcp = createBootclasspath();
String javaHome = System.getProperty("java.home");
StringBuffer bcpMember = new StringBuffer();
bcpMember.append(javaHome).append("/bin/default/jclSC170/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
+ bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ppc/default/jclSC170/vm.jar:");
+ bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/charsets.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/core.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/math.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/java.util.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/rt.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/graphics.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/javaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/jaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/security.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/server.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/JawBridge.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/gskikm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ibmjceprovider.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/indicim.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/jaccess.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ldapsec.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/oldcertpath.jar");
bcp.createPathElement().setPath(bcpMember.toString());
return bcp;
}
/**
* Checks whether the JDK version is 1.4 or higher. If it's not
* JDK 1.4 we check whether we're on a future JDK by checking
* that we're not on JDKs 1.0, 1.1, 1.2 or 1.3. This check by
* exclusion should future proof this task from new versions of
* Ant which are aware of higher JDK versions.
*
* @return true if the JDK version is 1.4 or higher.
*/
private boolean isJDK14OrHigher() {
final String version = JavaEnvUtils.getJavaVersion();
return version.equals(JavaEnvUtils.JAVA_1_4) ||
(!version.equals(JavaEnvUtils.JAVA_1_3) &&
!version.equals(JavaEnvUtils.JAVA_1_2) &&
!version.equals(JavaEnvUtils.JAVA_1_1) &&
!version.equals(JavaEnvUtils.JAVA_1_0));
}
}
| true | true | private Path createIBMJDKBootclasspath() {
Path bcp = createBootclasspath();
String javaHome = System.getProperty("java.home");
StringBuffer bcpMember = new StringBuffer();
bcpMember.append(javaHome).append("/bin/default/jclSC170/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/charsets.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/core.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/math.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/java.util.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/rt.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/graphics.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/javaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/jaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/security.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/server.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/JawBridge.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/gskikm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ibmjceprovider.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/indicim.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/jaccess.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ldapsec.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/oldcertpath.jar");
bcp.createPathElement().setPath(bcpMember.toString());
return bcp;
}
| private Path createIBMJDKBootclasspath() {
Path bcp = createBootclasspath();
String javaHome = System.getProperty("java.home");
StringBuffer bcpMember = new StringBuffer();
bcpMember.append(javaHome).append("/bin/default/jclSC170/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ppc/default/jclSC170/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/charsets.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/core.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/math.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/vm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/java.util.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/rt.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/graphics.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/javaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/jaws.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/security.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/server.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/JawBridge.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/gskikm.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ibmjceprovider.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/indicim.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/jaccess.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ldapsec.jar:");
bcp.createPathElement().setPath(bcpMember.toString());
bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/oldcertpath.jar");
bcp.createPathElement().setPath(bcpMember.toString());
return bcp;
}
|
diff --git a/src/java/com/samskivert/jdbc/depot/DepotMarshaller.java b/src/java/com/samskivert/jdbc/depot/DepotMarshaller.java
index 105efab1..3cbd0c7f 100644
--- a/src/java/com/samskivert/jdbc/depot/DepotMarshaller.java
+++ b/src/java/com/samskivert/jdbc/depot/DepotMarshaller.java
@@ -1,916 +1,918 @@
//
// $Id$
//
// samskivert library - useful routines for java programs
// Copyright (C) 2006 Michael Bayne, Pär Winzell
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.depot.annotation.Computed;
import com.samskivert.jdbc.depot.annotation.Entity;
import com.samskivert.jdbc.depot.annotation.GeneratedValue;
import com.samskivert.jdbc.depot.annotation.Id;
import com.samskivert.jdbc.depot.annotation.Index;
import com.samskivert.jdbc.depot.annotation.Table;
import com.samskivert.jdbc.depot.annotation.TableGenerator;
import com.samskivert.jdbc.depot.annotation.Transient;
import com.samskivert.jdbc.depot.annotation.UniqueConstraint;
import com.samskivert.jdbc.JDBCUtil;
import com.samskivert.jdbc.depot.clause.Where;
import com.samskivert.util.ArrayUtil;
import com.samskivert.util.ListUtil;
import com.samskivert.util.StringUtil;
import static com.samskivert.jdbc.depot.Log.log;
/**
* Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link
* PreparedStatement} and {@link ResultSet}).
*/
public class DepotMarshaller<T extends PersistentRecord>
{
/** The name of a private static field that must be defined for all persistent object classes.
* It is used to handle schema migration. If automatic schema migration is not desired, define
* this field and set its value to -1. */
public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION";
/**
* Creates a marshaller for the specified persistent object class.
*/
public DepotMarshaller (Class<T> pclass, PersistenceContext context)
{
_pclass = pclass;
Entity entity = pclass.getAnnotation(Entity.class);
Table table = null;
// see if this is a computed entity
Computed computed = pclass.getAnnotation(Computed.class);
if (computed == null) {
// if not, this class has a corresponding SQL table
_tableName = _pclass.getName();
_tableName = _tableName.substring(_tableName.lastIndexOf(".")+1);
// see if there are Entity values specified
if (entity != null) {
if (entity.name().length() > 0) {
_tableName = entity.name();
}
_postamble = entity.postamble();
}
// check for a Table annotation, for unique constraints
table = pclass.getAnnotation(Table.class);
}
// if the entity defines a new TableGenerator, map that in our static table as those are
// shared across all entities
TableGenerator generator = pclass.getAnnotation(TableGenerator.class);
if (generator != null) {
context.tableGenerators.put(generator.name(), generator);
}
// introspect on the class and create marshallers for persistent fields
ArrayList<String> fields = new ArrayList<String>();
for (Field field : _pclass.getFields()) {
int mods = field.getModifiers();
// check for a static constant schema version
if (java.lang.reflect.Modifier.isStatic(mods) &&
field.getName().equals(SCHEMA_VERSION_FIELD)) {
try {
_schemaVersion = (Integer)field.get(null);
} catch (Exception e) {
log.log(Level.WARNING, "Failed to read schema version " +
"[class=" + _pclass + "].", e);
}
}
// the field must be public, non-static and non-transient
if (!java.lang.reflect.Modifier.isPublic(mods) ||
java.lang.reflect.Modifier.isStatic(mods) ||
field.getAnnotation(Transient.class) != null) {
continue;
}
FieldMarshaller fm = FieldMarshaller.createMarshaller(field);
_fields.put(fm.getColumnName(), fm);
fields.add(fm.getColumnName());
// check to see if this is our primary key
if (field.getAnnotation(Id.class) != null) {
if (_pkColumns == null) {
_pkColumns = new ArrayList<FieldMarshaller>();
}
_pkColumns.add(fm);
// check if this field defines a new TableGenerator
generator = field.getAnnotation(TableGenerator.class);
if (generator != null) {
context.tableGenerators.put(generator.name(), generator);
}
}
}
// if the entity defines a single-columnar primary key, figure out if we will be generating
// values for it
if (_pkColumns != null) {
GeneratedValue gv = null;
FieldMarshaller keyField = null;
// loop over fields to see if there's a @GeneratedValue at all
for (FieldMarshaller field : _pkColumns) {
gv = field.getGeneratedValue();
if (gv != null) {
keyField = field;
break;
}
}
if (keyField != null) {
// and if there is, make sure we've a single-column id
if (_pkColumns.size() > 1) {
throw new IllegalArgumentException(
"Cannot use @GeneratedValue on multiple-column @Id's");
}
// the primary key must be numeric if we are to auto-assign it
Class<?> ftype = keyField.getField().getType();
boolean isNumeric = (
ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) ||
ftype.equals(Short.TYPE) || ftype.equals(Short.class) ||
ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) ||
ftype.equals(Long.TYPE) || ftype.equals(Long.class));
if (!isNumeric) {
throw new IllegalArgumentException(
"Cannot use @GeneratedValue on non-numeric column");
}
switch(gv.strategy()) {
case AUTO:
case IDENTITY:
_keyGenerator = new IdentityKeyGenerator();
break;
case TABLE:
String name = gv.generator();
generator = context.tableGenerators.get(name);
if (generator == null) {
throw new IllegalArgumentException(
"Unknown generator [generator=" + name + "]");
}
_keyGenerator = new TableKeyGenerator(generator);
break;
}
}
}
// generate our full list of fields/columns for use in queries
_allFields = fields.toArray(new String[fields.size()]);
// if we're a computed entity, stop here
if (_tableName == null) {
return;
}
// figure out the list of fields that correspond to actual table columns and generate the
// SQL used to create and migrate our table (unless we're a computed entity)
_columnFields = new String[_allFields.length];
int jj = 0;
for (int ii = 0; ii < _allFields.length; ii++) {
// include all persistent non-computed fields
String colDef = _fields.get(_allFields[ii]).getColumnDefinition();
if (colDef != null) {
_columnFields[jj] = _allFields[ii];
_declarations.add(colDef);
jj ++;
}
}
_columnFields = ArrayUtil.splice(_columnFields, jj);
// determine whether we have any index definitions
if (entity != null) {
for (Index index : entity.indices()) {
// TODO: delegate this to a database specific SQL generator
_declarations.add(index.type() + " index " + index.name() +
" (" + StringUtil.join(index.columns(), ", ") + ")");
}
}
// add any unique constraints given
if (table != null) {
for (UniqueConstraint constraint : table.uniqueConstraints()) {
_declarations.add(
"UNIQUE (" + StringUtil.join(constraint.columnNames(), ", ") + ")");
}
}
// add the primary key, if we have one
if (hasPrimaryKey()) {
_declarations.add("PRIMARY KEY (" + getPrimaryKeyColumns() + ")");
}
// if we did not find a schema version field, complain
if (_schemaVersion < 0) {
log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD +
". Schema migration disabled.");
}
}
/**
* Returns the name of the table in which persistence instances of this class are stored. By
* default this is the classname of the persistent object without the package.
*/
public String getTableName ()
{
return _tableName;
}
/**
* Returns true if our persistent object defines a primary key.
*/
public boolean hasPrimaryKey ()
{
return (_pkColumns != null);
}
/**
* Returns a key configured with the primary key of the supplied object. If all the fields are
* null, this method returns null. An exception is thrown if some of the fields are null and
* some are not, or if the object does not declare a primary key.
*/
public Key<T> getPrimaryKey (Object object)
{
return getPrimaryKey(object, true);
}
/**
* Returns a key configured with the primary key of the supplied object. If all the fields are
* null, this method returns null. If some of the fields are null and some are not, an
* exception is thrown. If the object does not declare a primary key and the second argument is
* true, this method throws an exception; if it's false, the method returns null.
*/
public Key<T> getPrimaryKey (Object object, boolean requireKey)
{
if (!hasPrimaryKey()) {
if (requireKey) {
throw new UnsupportedOperationException(
_pclass.getName() + " does not define a primary key");
}
return null;
}
try {
Comparable[] values = new Comparable[_pkColumns.size()];
boolean hasNulls = false;
for (int ii = 0; ii < _pkColumns.size(); ii++) {
FieldMarshaller field = _pkColumns.get(ii);
values[ii] = (Comparable) field.getField().get(object);
if (values[ii] == null || Integer.valueOf(0).equals(values[ii])) {
// if this is the first null we see but not the first field, freak out
if (!hasNulls && ii > 0) {
throw new IllegalArgumentException(
"Persistent object's primary key fields are mixed null and non-null.");
}
hasNulls = true;
} else if (hasNulls) {
// if this is a non-null field and we've previously seen nulls, also freak
throw new IllegalArgumentException(
"Persistent object's primary key fields are mixed null and non-null.");
}
}
// if all the fields were null, return null, else build a key
return hasNulls ? null : makePrimaryKey(values);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
}
}
/**
* Creates a primary key record for the type of object handled by this marshaller, using the
* supplied primary key value.
*/
public Key<T> makePrimaryKey (Comparable... values)
{
if (!hasPrimaryKey()) {
throw new UnsupportedOperationException(
getClass().getName() + " does not define a primary key");
}
String[] columns = new String[_pkColumns.size()];
for (int ii = 0; ii < _pkColumns.size(); ii++) {
columns[ii] = _pkColumns.get(ii).getColumnName();
}
return new Key<T>(_pclass, columns, values);
}
/**
* Returns true if this marshaller has been initialized ({@link #init} has been called), its
* migrations run and it is ready for operation. False otherwise.
*/
public boolean isInitialized ()
{
return _initialized;
}
/**
* Creates a persistent object from the supplied result set. The result set must have come from
* a query provided by {@link #createQuery}.
*/
public T createObject (ResultSet rs)
throws SQLException
{
try {
// first, build a set of the fields that we actually received
Set<String> fields = new HashSet<String>();
ResultSetMetaData metadata = rs.getMetaData();
for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) {
fields.add(metadata.getColumnName(ii));
}
// then create and populate the persistent object
T po = _pclass.newInstance();
for (FieldMarshaller fm : _fields.values()) {
if (!fields.contains(fm.getField().getName())) {
// this field was not in the result set, make sure that's OK
if (fm.getComputed() != null && !fm.getComputed().required()) {
continue;
}
throw new SQLException("ResultSet missing field: " + fm.getField().getName());
}
fm.getValue(rs, po);
}
return po;
} catch (SQLException sqe) {
// pass this on through
throw sqe;
} catch (Exception e) {
String errmsg = "Failed to unmarshall persistent object [pclass=" +
_pclass.getName() + "]";
throw (SQLException)new SQLException(errmsg).initCause(e);
}
}
/**
* Creates a statement that will insert the supplied persistent object into the database.
*/
public PreparedStatement createInsert (Connection conn, Object po)
throws SQLException
{
requireNotComputed("insert rows into");
try {
StringBuilder insert = new StringBuilder();
insert.append("insert into ").append(getTableName());
insert.append(" (").append(StringUtil.join(_columnFields, ","));
insert.append(")").append(" values(");
for (int ii = 0; ii < _columnFields.length; ii++) {
if (ii > 0) {
insert.append(", ");
}
insert.append("?");
}
insert.append(")");
// TODO: handle primary key, nullable fields specially?
PreparedStatement pstmt = conn.prepareStatement(insert.toString());
int idx = 0;
for (String field : _columnFields) {
_fields.get(field).setValue(po, pstmt, ++idx);
}
return pstmt;
} catch (SQLException sqe) {
// pass this on through
throw sqe;
} catch (Exception e) {
String errmsg = "Failed to marshall persistent object [pclass=" +
_pclass.getName() + "]";
throw (SQLException)new SQLException(errmsg).initCause(e);
}
}
/**
* Fills in the primary key just assigned to the supplied persistence object by the execution
* of the results of {@link #createInsert}.
*
* @return the newly assigned primary key or null if the object does not use primary keys or
* this is not the right time to assign the key.
*/
public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum)
throws SQLException
{
// if we have no primary key or no generator, then we're done
if (!hasPrimaryKey() || _keyGenerator == null) {
return null;
}
// run this generator either before or after the actual insertion
if (_keyGenerator.isPostFactum() != postFactum) {
return null;
}
try {
int nextValue = _keyGenerator.nextGeneratedValue(conn);
_pkColumns.get(0).getField().set(po, nextValue);
return makePrimaryKey(nextValue);
} catch (Exception e) {
String errmsg = "Failed to assign primary key [type=" + _pclass + "]";
throw (SQLException) new SQLException(errmsg).initCause(e);
}
}
/**
* Creates a statement that will update the supplied persistent object using the supplied key.
*/
public PreparedStatement createUpdate (Connection conn, Object po, Where key)
throws SQLException
{
return createUpdate(conn, po, key, _columnFields);
}
/**
* Creates a statement that will update the supplied persistent object
* using the supplied key.
*/
public PreparedStatement createUpdate (
Connection conn, Object po, Where key, String[] modifiedFields)
throws SQLException
{
requireNotComputed("update rows in");
StringBuilder update = new StringBuilder();
update.append("update ").append(getTableName()).append(" set ");
int idx = 0;
for (String field : modifiedFields) {
if (idx++ > 0) {
update.append(", ");
}
update.append(field).append(" = ?");
}
key.appendClause(null, update);
try {
PreparedStatement pstmt = conn.prepareStatement(update.toString());
idx = 0;
// bind the update arguments
for (String field : modifiedFields) {
_fields.get(field).setValue(po, pstmt, ++idx);
}
// now bind the key arguments
key.bindArguments(pstmt, ++idx);
return pstmt;
} catch (SQLException sqe) {
// pass this on through
throw sqe;
} catch (Exception e) {
String errmsg = "Failed to marshall persistent object " +
"[pclass=" + _pclass.getName() + "]";
throw (SQLException)new SQLException(errmsg).initCause(e);
}
}
/**
* Creates a statement that will update the specified set of fields for all persistent objects
* that match the supplied key.
*/
public PreparedStatement createPartialUpdate (
Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues)
throws SQLException
{
requireNotComputed("update rows in");
StringBuilder update = new StringBuilder();
update.append("update ").append(getTableName()).append(" set ");
int idx = 0;
for (String field : modifiedFields) {
if (idx++ > 0) {
update.append(", ");
}
update.append(field).append(" = ?");
}
key.appendClause(null, update);
PreparedStatement pstmt = conn.prepareStatement(update.toString());
idx = 0;
// bind the update arguments
for (Object value : modifiedValues) {
// TODO: use the field marshaller?
pstmt.setObject(++idx, value);
}
// now bind the key arguments
key.bindArguments(pstmt, ++idx);
return pstmt;
}
/**
* Creates a statement that will delete all rows matching the supplied key.
*/
public PreparedStatement createDelete (Connection conn, Where key)
throws SQLException
{
requireNotComputed("delete rows from");
StringBuilder query = new StringBuilder("delete from " + getTableName());
key.appendClause(null, query);
PreparedStatement pstmt = conn.prepareStatement(query.toString());
key.bindArguments(pstmt, 1);
return pstmt;
}
/**
* Creates a statement that will update the specified set of fields, using the supplied literal
* SQL values, for all persistent objects that match the supplied key.
*/
public PreparedStatement createLiteralUpdate (
Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues)
throws SQLException
{
requireNotComputed("update rows in");
StringBuilder update = new StringBuilder();
update.append("update ").append(getTableName()).append(" set ");
for (int ii = 0; ii < modifiedFields.length; ii++) {
if (ii > 0) {
update.append(", ");
}
update.append(modifiedFields[ii]).append(" = ");
update.append(modifiedValues[ii]);
}
key.appendClause(null, update);
PreparedStatement pstmt = conn.prepareStatement(update.toString());
key.bindArguments(pstmt, 1);
return pstmt;
}
/**
* This is called by the persistence context to register a migration for the entity managed by
* this marshaller.
*/
protected void registerMigration (EntityMigration migration)
{
_migrations.add(migration);
}
/**
* Initializes the table used by this marshaller. This is called automatically by the {@link
* PersistenceContext} the first time an entity is used. If the table does not exist, it will
* be created. If the schema version specified by the persistent object is newer than the
* database schema, it will be migrated.
*/
protected void init (PersistenceContext ctx)
throws PersistenceException
{
if (_initialized) { // sanity check
throw new IllegalStateException(
"Cannot re-initialize marshaller [type=" + _pclass + "].");
}
_initialized = true;
// if we have no table (i.e. we're a computed entity), we have nothing to create
if (getTableName() == null) {
return;
}
// check to see if our schema version table exists, create it if not
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
JDBCUtil.createTableIfMissing(
conn, SCHEMA_VERSION_TABLE,
new String[] { "persistentClass VARCHAR(255) NOT NULL",
"version INTEGER NOT NULL" }, "");
return 0;
}
});
// now create the table for our persistent class if it does not exist
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
if (!JDBCUtil.tableExists(conn, getTableName())) {
log.info("Creating table " + getTableName() + " (" + _declarations + ") " +
_postamble);
String[] definition = _declarations.toArray(new String[_declarations.size()]);
JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble);
updateVersion(conn, 1);
}
return 0;
}
});
// if we have a key generator, initialize that too
if (_keyGenerator != null) {
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
_keyGenerator.init(conn);
return 0;
}
});
}
// if schema versioning is disabled, stop now
if (_schemaVersion < 0) {
return;
}
// make sure the versions match
int currentVersion = ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
String query = "select version from " + SCHEMA_VERSION_TABLE +
" where persistentClass = '" + getTableName() + "'";
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
return (rs.next()) ? rs.getInt(1) : 1;
} finally {
stmt.close();
}
}
});
if (currentVersion == _schemaVersion) {
return;
}
// otherwise try to migrate the schema
log.info("Migrating " + getTableName() + " from " +
currentVersion + " to " + _schemaVersion + "...");
// run our pre-default-migrations
for (EntityMigration migration : _migrations) {
if (migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// enumerate all of the columns now that we've run our pre-migrations
final Set<String> columns = new HashSet<String>();
final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>();
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null, null, getTableName(), "%");
while (rs.next()) {
columns.add(rs.getString("COLUMN_NAME"));
}
rs = meta.getIndexInfo(null, null, getTableName(), false, false);
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
Set<String> set = indexColumns.get(indexName);
if (rs.getBoolean("NON_UNIQUE")) {
// not a unique index: just make sure there's an entry in the keyset
if (set == null) {
indexColumns.put(indexName, null);
}
} else {
// for unique indices we collect the column names
if (set == null) {
set = new HashSet<String>();
indexColumns.put(indexName, set);
}
set.add(rs.getString("COLUMN_NAME"));
}
}
return 0;
}
});
// this is a little silly, but we need a copy for name disambiguation later
Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet());
// add any missing columns
for (String fname : _columnFields) {
FieldMarshaller fmarsh = _fields.get(fname);
if (columns.remove(fmarsh.getColumnName())) {
continue;
}
// otherwise add the column
String coldef = fmarsh.getColumnDefinition();
String query = "alter table " + getTableName() + " add column " + coldef;
// try to add it to the appropriate spot
int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName());
if (fidx == 0) {
query += " first";
} else {
query += " after " + _allFields[fidx-1];
}
log.info("Adding column to " + getTableName() + ": " + coldef);
ctx.invoke(new Modifier.Simple(query));
// if the column is a TIMESTAMP column, we need to run a special query to update all
// existing rows to the current time because MySQL annoyingly assigns them a default
// value of "0000-00-00 00:00:00" regardless of whether we explicitly provide a
// "DEFAULT" value for the column or not
if (coldef.toLowerCase().indexOf(" timestamp") != -1) {
query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()";
log.info("Assigning current time to TIMESTAMP column: " + query);
ctx.invoke(new Modifier.Simple(query));
}
}
// add or remove the primary key as needed
if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) {
String pkdef = "primary key (" + getPrimaryKeyColumns() + ")";
log.info("Adding primary key to " + getTableName() + ": " + pkdef);
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef));
- } else if (!hasPrimaryKey() && indexColumns.remove("PRIMARY") != null) {
+ } else if (!hasPrimaryKey() && indexColumns.containsKey("PRIMARY")) {
+ indexColumns.remove("PRIMARY");
log.info("Dropping primary from " + getTableName());
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key"));
}
// add any missing indices
Entity entity = _pclass.getAnnotation(Entity.class);
for (Index index : (entity == null ? new Index[0] : entity.indices())) {
- if (indexColumns.remove(index.name()) != null) {
+ if (indexColumns.containsKey(index.name())) {
+ indexColumns.remove(index.name());
continue;
}
String indexdef = "create " + index.type() + " index " + index.name() +
" on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")";
log.info("Adding index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
// to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets
Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values());
Table table;
if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) {
Set<String> colSet = new HashSet<String>();
for (UniqueConstraint constraint : table.uniqueConstraints()) {
// for each given UniqueConstraint, build a new column set
colSet.clear();
for (String column : constraint.columnNames()) {
colSet.add(column);
}
// and check if the table contained this set
if (uniqueIndices.contains(colSet)) {
continue; // good, carry on
}
// else build the index; we'll use mysql's convention of naming it after a column,
// with possible _N disambiguation; luckily we made a copy of the index names!
String indexName = colSet.iterator().next();
if (indicesCopy.contains(indexName)) {
int num = 1;
indexName += "_";
while (indicesCopy.contains(indexName + num)) {
num ++;
}
indexName += num;
}
String[] columnArr = colSet.toArray(new String[colSet.size()]);
String indexdef = "create unique index " + indexName + " on " +
getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")";
log.info("Adding unique index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
}
// we do not auto-remove columns but rather require that EntityMigration.Drop records be
// registered by hand to avoid accidentally causin the loss of data
// we don't auto-remove indices either because we'd have to sort out the potentially
// complex origins of an index (which might be because of a @Unique column or maybe the
// index was hand defined in a @Column clause)
// run our post-default-migrations
for (EntityMigration migration : _migrations) {
if (!migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// record our new version in the database
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
updateVersion(conn, _schemaVersion);
return 0;
}
});
}
protected String getPrimaryKeyColumns ()
{
String[] pkcols = new String[_pkColumns.size()];
for (int ii = 0; ii < pkcols.length; ii ++) {
pkcols[ii] = _pkColumns.get(ii).getColumnName();
}
return StringUtil.join(pkcols, ", ");
}
protected void updateVersion (Connection conn, int version)
throws SQLException
{
String update = "update " + SCHEMA_VERSION_TABLE +
" set version = " + version + " where persistentClass = '" + getTableName() + "'";
String insert = "insert into " + SCHEMA_VERSION_TABLE +
" values('" + getTableName() + "', " + version + ")";
Statement stmt = conn.createStatement();
try {
if (stmt.executeUpdate(update) == 0) {
stmt.executeUpdate(insert);
}
} finally {
stmt.close();
}
}
protected void requireNotComputed (String action)
throws SQLException
{
if (getTableName() == null) {
throw new IllegalArgumentException(
"Can't " + action + " computed entities [class=" + _pclass + "]");
}
}
/** The persistent object class that we manage. */
protected Class<T> _pclass;
/** The name of our persistent object table. */
protected String _tableName;
/** A field marshaller for each persistent field in our object. */
protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>();
/** The field marshallers for our persistent object's primary key columns
* or null if it did not define a primary key. */
protected ArrayList<FieldMarshaller> _pkColumns;
/** The generator to use for auto-generating primary key values, or null. */
protected KeyGenerator _keyGenerator;
/** The persisent fields of our object, in definition order. */
protected String[] _allFields;
/** The fields of our object with directly corresponding table columns. */
protected String[] _columnFields;
/** The version of our persistent object schema as specified in the class
* definition. */
protected int _schemaVersion = -1;
/** Used when creating and migrating our table schema. */
protected ArrayList<String> _declarations = new ArrayList<String>();
/** Used when creating and migrating our table schema. */
protected String _postamble = "";
/** Indicates that we have been initialized (created or migrated our tables). */
protected boolean _initialized;
/** A list of hand registered entity migrations to run prior to doing the default migration. */
protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>();
/** The name of the table we use to track schema versions. */
protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion";
}
| false | true | protected void init (PersistenceContext ctx)
throws PersistenceException
{
if (_initialized) { // sanity check
throw new IllegalStateException(
"Cannot re-initialize marshaller [type=" + _pclass + "].");
}
_initialized = true;
// if we have no table (i.e. we're a computed entity), we have nothing to create
if (getTableName() == null) {
return;
}
// check to see if our schema version table exists, create it if not
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
JDBCUtil.createTableIfMissing(
conn, SCHEMA_VERSION_TABLE,
new String[] { "persistentClass VARCHAR(255) NOT NULL",
"version INTEGER NOT NULL" }, "");
return 0;
}
});
// now create the table for our persistent class if it does not exist
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
if (!JDBCUtil.tableExists(conn, getTableName())) {
log.info("Creating table " + getTableName() + " (" + _declarations + ") " +
_postamble);
String[] definition = _declarations.toArray(new String[_declarations.size()]);
JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble);
updateVersion(conn, 1);
}
return 0;
}
});
// if we have a key generator, initialize that too
if (_keyGenerator != null) {
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
_keyGenerator.init(conn);
return 0;
}
});
}
// if schema versioning is disabled, stop now
if (_schemaVersion < 0) {
return;
}
// make sure the versions match
int currentVersion = ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
String query = "select version from " + SCHEMA_VERSION_TABLE +
" where persistentClass = '" + getTableName() + "'";
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
return (rs.next()) ? rs.getInt(1) : 1;
} finally {
stmt.close();
}
}
});
if (currentVersion == _schemaVersion) {
return;
}
// otherwise try to migrate the schema
log.info("Migrating " + getTableName() + " from " +
currentVersion + " to " + _schemaVersion + "...");
// run our pre-default-migrations
for (EntityMigration migration : _migrations) {
if (migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// enumerate all of the columns now that we've run our pre-migrations
final Set<String> columns = new HashSet<String>();
final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>();
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null, null, getTableName(), "%");
while (rs.next()) {
columns.add(rs.getString("COLUMN_NAME"));
}
rs = meta.getIndexInfo(null, null, getTableName(), false, false);
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
Set<String> set = indexColumns.get(indexName);
if (rs.getBoolean("NON_UNIQUE")) {
// not a unique index: just make sure there's an entry in the keyset
if (set == null) {
indexColumns.put(indexName, null);
}
} else {
// for unique indices we collect the column names
if (set == null) {
set = new HashSet<String>();
indexColumns.put(indexName, set);
}
set.add(rs.getString("COLUMN_NAME"));
}
}
return 0;
}
});
// this is a little silly, but we need a copy for name disambiguation later
Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet());
// add any missing columns
for (String fname : _columnFields) {
FieldMarshaller fmarsh = _fields.get(fname);
if (columns.remove(fmarsh.getColumnName())) {
continue;
}
// otherwise add the column
String coldef = fmarsh.getColumnDefinition();
String query = "alter table " + getTableName() + " add column " + coldef;
// try to add it to the appropriate spot
int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName());
if (fidx == 0) {
query += " first";
} else {
query += " after " + _allFields[fidx-1];
}
log.info("Adding column to " + getTableName() + ": " + coldef);
ctx.invoke(new Modifier.Simple(query));
// if the column is a TIMESTAMP column, we need to run a special query to update all
// existing rows to the current time because MySQL annoyingly assigns them a default
// value of "0000-00-00 00:00:00" regardless of whether we explicitly provide a
// "DEFAULT" value for the column or not
if (coldef.toLowerCase().indexOf(" timestamp") != -1) {
query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()";
log.info("Assigning current time to TIMESTAMP column: " + query);
ctx.invoke(new Modifier.Simple(query));
}
}
// add or remove the primary key as needed
if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) {
String pkdef = "primary key (" + getPrimaryKeyColumns() + ")";
log.info("Adding primary key to " + getTableName() + ": " + pkdef);
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef));
} else if (!hasPrimaryKey() && indexColumns.remove("PRIMARY") != null) {
log.info("Dropping primary from " + getTableName());
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key"));
}
// add any missing indices
Entity entity = _pclass.getAnnotation(Entity.class);
for (Index index : (entity == null ? new Index[0] : entity.indices())) {
if (indexColumns.remove(index.name()) != null) {
continue;
}
String indexdef = "create " + index.type() + " index " + index.name() +
" on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")";
log.info("Adding index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
// to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets
Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values());
Table table;
if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) {
Set<String> colSet = new HashSet<String>();
for (UniqueConstraint constraint : table.uniqueConstraints()) {
// for each given UniqueConstraint, build a new column set
colSet.clear();
for (String column : constraint.columnNames()) {
colSet.add(column);
}
// and check if the table contained this set
if (uniqueIndices.contains(colSet)) {
continue; // good, carry on
}
// else build the index; we'll use mysql's convention of naming it after a column,
// with possible _N disambiguation; luckily we made a copy of the index names!
String indexName = colSet.iterator().next();
if (indicesCopy.contains(indexName)) {
int num = 1;
indexName += "_";
while (indicesCopy.contains(indexName + num)) {
num ++;
}
indexName += num;
}
String[] columnArr = colSet.toArray(new String[colSet.size()]);
String indexdef = "create unique index " + indexName + " on " +
getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")";
log.info("Adding unique index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
}
// we do not auto-remove columns but rather require that EntityMigration.Drop records be
// registered by hand to avoid accidentally causin the loss of data
// we don't auto-remove indices either because we'd have to sort out the potentially
// complex origins of an index (which might be because of a @Unique column or maybe the
// index was hand defined in a @Column clause)
// run our post-default-migrations
for (EntityMigration migration : _migrations) {
if (!migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// record our new version in the database
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
updateVersion(conn, _schemaVersion);
return 0;
}
});
}
protected String getPrimaryKeyColumns ()
{
String[] pkcols = new String[_pkColumns.size()];
for (int ii = 0; ii < pkcols.length; ii ++) {
pkcols[ii] = _pkColumns.get(ii).getColumnName();
}
return StringUtil.join(pkcols, ", ");
}
protected void updateVersion (Connection conn, int version)
throws SQLException
{
String update = "update " + SCHEMA_VERSION_TABLE +
" set version = " + version + " where persistentClass = '" + getTableName() + "'";
String insert = "insert into " + SCHEMA_VERSION_TABLE +
" values('" + getTableName() + "', " + version + ")";
Statement stmt = conn.createStatement();
try {
if (stmt.executeUpdate(update) == 0) {
stmt.executeUpdate(insert);
}
} finally {
stmt.close();
}
}
protected void requireNotComputed (String action)
throws SQLException
{
if (getTableName() == null) {
throw new IllegalArgumentException(
"Can't " + action + " computed entities [class=" + _pclass + "]");
}
}
/** The persistent object class that we manage. */
protected Class<T> _pclass;
/** The name of our persistent object table. */
protected String _tableName;
/** A field marshaller for each persistent field in our object. */
protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>();
/** The field marshallers for our persistent object's primary key columns
* or null if it did not define a primary key. */
protected ArrayList<FieldMarshaller> _pkColumns;
/** The generator to use for auto-generating primary key values, or null. */
protected KeyGenerator _keyGenerator;
/** The persisent fields of our object, in definition order. */
protected String[] _allFields;
/** The fields of our object with directly corresponding table columns. */
protected String[] _columnFields;
/** The version of our persistent object schema as specified in the class
* definition. */
protected int _schemaVersion = -1;
/** Used when creating and migrating our table schema. */
protected ArrayList<String> _declarations = new ArrayList<String>();
/** Used when creating and migrating our table schema. */
protected String _postamble = "";
/** Indicates that we have been initialized (created or migrated our tables). */
protected boolean _initialized;
/** A list of hand registered entity migrations to run prior to doing the default migration. */
protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>();
/** The name of the table we use to track schema versions. */
protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion";
}
| protected void init (PersistenceContext ctx)
throws PersistenceException
{
if (_initialized) { // sanity check
throw new IllegalStateException(
"Cannot re-initialize marshaller [type=" + _pclass + "].");
}
_initialized = true;
// if we have no table (i.e. we're a computed entity), we have nothing to create
if (getTableName() == null) {
return;
}
// check to see if our schema version table exists, create it if not
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
JDBCUtil.createTableIfMissing(
conn, SCHEMA_VERSION_TABLE,
new String[] { "persistentClass VARCHAR(255) NOT NULL",
"version INTEGER NOT NULL" }, "");
return 0;
}
});
// now create the table for our persistent class if it does not exist
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
if (!JDBCUtil.tableExists(conn, getTableName())) {
log.info("Creating table " + getTableName() + " (" + _declarations + ") " +
_postamble);
String[] definition = _declarations.toArray(new String[_declarations.size()]);
JDBCUtil.createTableIfMissing(conn, getTableName(), definition, _postamble);
updateVersion(conn, 1);
}
return 0;
}
});
// if we have a key generator, initialize that too
if (_keyGenerator != null) {
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
_keyGenerator.init(conn);
return 0;
}
});
}
// if schema versioning is disabled, stop now
if (_schemaVersion < 0) {
return;
}
// make sure the versions match
int currentVersion = ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
String query = "select version from " + SCHEMA_VERSION_TABLE +
" where persistentClass = '" + getTableName() + "'";
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
return (rs.next()) ? rs.getInt(1) : 1;
} finally {
stmt.close();
}
}
});
if (currentVersion == _schemaVersion) {
return;
}
// otherwise try to migrate the schema
log.info("Migrating " + getTableName() + " from " +
currentVersion + " to " + _schemaVersion + "...");
// run our pre-default-migrations
for (EntityMigration migration : _migrations) {
if (migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// enumerate all of the columns now that we've run our pre-migrations
final Set<String> columns = new HashSet<String>();
final Map<String, Set<String>> indexColumns = new HashMap<String, Set<String>>();
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null, null, getTableName(), "%");
while (rs.next()) {
columns.add(rs.getString("COLUMN_NAME"));
}
rs = meta.getIndexInfo(null, null, getTableName(), false, false);
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
Set<String> set = indexColumns.get(indexName);
if (rs.getBoolean("NON_UNIQUE")) {
// not a unique index: just make sure there's an entry in the keyset
if (set == null) {
indexColumns.put(indexName, null);
}
} else {
// for unique indices we collect the column names
if (set == null) {
set = new HashSet<String>();
indexColumns.put(indexName, set);
}
set.add(rs.getString("COLUMN_NAME"));
}
}
return 0;
}
});
// this is a little silly, but we need a copy for name disambiguation later
Set<String> indicesCopy = new HashSet<String>(indexColumns.keySet());
// add any missing columns
for (String fname : _columnFields) {
FieldMarshaller fmarsh = _fields.get(fname);
if (columns.remove(fmarsh.getColumnName())) {
continue;
}
// otherwise add the column
String coldef = fmarsh.getColumnDefinition();
String query = "alter table " + getTableName() + " add column " + coldef;
// try to add it to the appropriate spot
int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName());
if (fidx == 0) {
query += " first";
} else {
query += " after " + _allFields[fidx-1];
}
log.info("Adding column to " + getTableName() + ": " + coldef);
ctx.invoke(new Modifier.Simple(query));
// if the column is a TIMESTAMP column, we need to run a special query to update all
// existing rows to the current time because MySQL annoyingly assigns them a default
// value of "0000-00-00 00:00:00" regardless of whether we explicitly provide a
// "DEFAULT" value for the column or not
if (coldef.toLowerCase().indexOf(" timestamp") != -1) {
query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()";
log.info("Assigning current time to TIMESTAMP column: " + query);
ctx.invoke(new Modifier.Simple(query));
}
}
// add or remove the primary key as needed
if (hasPrimaryKey() && !indexColumns.containsKey("PRIMARY")) {
String pkdef = "primary key (" + getPrimaryKeyColumns() + ")";
log.info("Adding primary key to " + getTableName() + ": " + pkdef);
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " add " + pkdef));
} else if (!hasPrimaryKey() && indexColumns.containsKey("PRIMARY")) {
indexColumns.remove("PRIMARY");
log.info("Dropping primary from " + getTableName());
ctx.invoke(new Modifier.Simple("alter table " + getTableName() + " drop primary key"));
}
// add any missing indices
Entity entity = _pclass.getAnnotation(Entity.class);
for (Index index : (entity == null ? new Index[0] : entity.indices())) {
if (indexColumns.containsKey(index.name())) {
indexColumns.remove(index.name());
continue;
}
String indexdef = "create " + index.type() + " index " + index.name() +
" on " + getTableName() + " (" + StringUtil.join(index.columns(), ", ") + ")";
log.info("Adding index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
// to get the @Table(uniqueIndices...) indices, we use our clever set of column name sets
Set<Set<String>> uniqueIndices = new HashSet<Set<String>>(indexColumns.values());
Table table;
if (getTableName() != null && (table = _pclass.getAnnotation(Table.class)) != null) {
Set<String> colSet = new HashSet<String>();
for (UniqueConstraint constraint : table.uniqueConstraints()) {
// for each given UniqueConstraint, build a new column set
colSet.clear();
for (String column : constraint.columnNames()) {
colSet.add(column);
}
// and check if the table contained this set
if (uniqueIndices.contains(colSet)) {
continue; // good, carry on
}
// else build the index; we'll use mysql's convention of naming it after a column,
// with possible _N disambiguation; luckily we made a copy of the index names!
String indexName = colSet.iterator().next();
if (indicesCopy.contains(indexName)) {
int num = 1;
indexName += "_";
while (indicesCopy.contains(indexName + num)) {
num ++;
}
indexName += num;
}
String[] columnArr = colSet.toArray(new String[colSet.size()]);
String indexdef = "create unique index " + indexName + " on " +
getTableName() + " (" + StringUtil.join(columnArr, ", ") + ")";
log.info("Adding unique index: " + indexdef);
ctx.invoke(new Modifier.Simple(indexdef));
}
}
// we do not auto-remove columns but rather require that EntityMigration.Drop records be
// registered by hand to avoid accidentally causin the loss of data
// we don't auto-remove indices either because we'd have to sort out the potentially
// complex origins of an index (which might be because of a @Unique column or maybe the
// index was hand defined in a @Column clause)
// run our post-default-migrations
for (EntityMigration migration : _migrations) {
if (!migration.runBeforeDefault() &&
migration.shouldRunMigration(currentVersion, _schemaVersion)) {
ctx.invoke(migration);
}
}
// record our new version in the database
ctx.invoke(new Modifier() {
public int invoke (Connection conn) throws SQLException {
updateVersion(conn, _schemaVersion);
return 0;
}
});
}
protected String getPrimaryKeyColumns ()
{
String[] pkcols = new String[_pkColumns.size()];
for (int ii = 0; ii < pkcols.length; ii ++) {
pkcols[ii] = _pkColumns.get(ii).getColumnName();
}
return StringUtil.join(pkcols, ", ");
}
protected void updateVersion (Connection conn, int version)
throws SQLException
{
String update = "update " + SCHEMA_VERSION_TABLE +
" set version = " + version + " where persistentClass = '" + getTableName() + "'";
String insert = "insert into " + SCHEMA_VERSION_TABLE +
" values('" + getTableName() + "', " + version + ")";
Statement stmt = conn.createStatement();
try {
if (stmt.executeUpdate(update) == 0) {
stmt.executeUpdate(insert);
}
} finally {
stmt.close();
}
}
protected void requireNotComputed (String action)
throws SQLException
{
if (getTableName() == null) {
throw new IllegalArgumentException(
"Can't " + action + " computed entities [class=" + _pclass + "]");
}
}
/** The persistent object class that we manage. */
protected Class<T> _pclass;
/** The name of our persistent object table. */
protected String _tableName;
/** A field marshaller for each persistent field in our object. */
protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>();
/** The field marshallers for our persistent object's primary key columns
* or null if it did not define a primary key. */
protected ArrayList<FieldMarshaller> _pkColumns;
/** The generator to use for auto-generating primary key values, or null. */
protected KeyGenerator _keyGenerator;
/** The persisent fields of our object, in definition order. */
protected String[] _allFields;
/** The fields of our object with directly corresponding table columns. */
protected String[] _columnFields;
/** The version of our persistent object schema as specified in the class
* definition. */
protected int _schemaVersion = -1;
/** Used when creating and migrating our table schema. */
protected ArrayList<String> _declarations = new ArrayList<String>();
/** Used when creating and migrating our table schema. */
protected String _postamble = "";
/** Indicates that we have been initialized (created or migrated our tables). */
protected boolean _initialized;
/** A list of hand registered entity migrations to run prior to doing the default migration. */
protected ArrayList<EntityMigration> _migrations = new ArrayList<EntityMigration>();
/** The name of the table we use to track schema versions. */
protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion";
}
|
diff --git a/IrcBot/src/org/snack/irc/handler/TranslateHandler.java b/IrcBot/src/org/snack/irc/handler/TranslateHandler.java
index e99ee02..fab521a 100644
--- a/IrcBot/src/org/snack/irc/handler/TranslateHandler.java
+++ b/IrcBot/src/org/snack/irc/handler/TranslateHandler.java
@@ -1,34 +1,38 @@
package org.snack.irc.handler;
import org.pircbotx.hooks.events.MessageEvent;
import org.snack.irc.settings.Config;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class TranslateHandler {
/**
* Translates text using the Bing translate API
*
* @param event
*/
public static void translate(MessageEvent<?> event) {
String text = event.getMessage().substring(11); // Cut off the command
// Set your Windows Azure Marketplace client info - See
// http://msdn.microsoft.com/en-us/library/hh454950.aspx
- Translate.setClientId("Snack-Ircbot");
- Translate.setClientSecret("ZCUBUZxekDrqvkKWPGriMQdHw7yGSut4YgaFvioUFEU=");
+ Translate.setClientId("92ef8ea3-08d0-4642-8f7c-af1898ac47b6");
+ Translate.setClientSecret("i4nycktHpUOs5eTgvo1AabpVSUGPqbgrVydJF2nVmtM=");
String translatedText = "";
try {
+ String response = Translate.execute(text, Language.AUTO_DETECT, Language.ENGLISH);
+ if (response.startsWith("TranslateApiException:")) {
+ throw new Exception();
+ }
translatedText = Config.speech.get("TR_SUC").replace("<response>", Translate.execute(text, Language.AUTO_DETECT, Language.ENGLISH));
} catch (Exception e) {
- // e.printStackTrace();
+ e.printStackTrace();
translatedText = Config.speech.get("TR_ERR");
}
event.getBot().sendMessage(event.getChannel(), translatedText);
}
}
| false | true | public static void translate(MessageEvent<?> event) {
String text = event.getMessage().substring(11); // Cut off the command
// Set your Windows Azure Marketplace client info - See
// http://msdn.microsoft.com/en-us/library/hh454950.aspx
Translate.setClientId("Snack-Ircbot");
Translate.setClientSecret("ZCUBUZxekDrqvkKWPGriMQdHw7yGSut4YgaFvioUFEU=");
String translatedText = "";
try {
translatedText = Config.speech.get("TR_SUC").replace("<response>", Translate.execute(text, Language.AUTO_DETECT, Language.ENGLISH));
} catch (Exception e) {
// e.printStackTrace();
translatedText = Config.speech.get("TR_ERR");
}
event.getBot().sendMessage(event.getChannel(), translatedText);
}
| public static void translate(MessageEvent<?> event) {
String text = event.getMessage().substring(11); // Cut off the command
// Set your Windows Azure Marketplace client info - See
// http://msdn.microsoft.com/en-us/library/hh454950.aspx
Translate.setClientId("92ef8ea3-08d0-4642-8f7c-af1898ac47b6");
Translate.setClientSecret("i4nycktHpUOs5eTgvo1AabpVSUGPqbgrVydJF2nVmtM=");
String translatedText = "";
try {
String response = Translate.execute(text, Language.AUTO_DETECT, Language.ENGLISH);
if (response.startsWith("TranslateApiException:")) {
throw new Exception();
}
translatedText = Config.speech.get("TR_SUC").replace("<response>", Translate.execute(text, Language.AUTO_DETECT, Language.ENGLISH));
} catch (Exception e) {
e.printStackTrace();
translatedText = Config.speech.get("TR_ERR");
}
event.getBot().sendMessage(event.getChannel(), translatedText);
}
|
diff --git a/src/java/org/apache/ddlutils/platform/mssql/MSSqlBuilder.java b/src/java/org/apache/ddlutils/platform/mssql/MSSqlBuilder.java
index 0f7051c..684d39b 100644
--- a/src/java/org/apache/ddlutils/platform/mssql/MSSqlBuilder.java
+++ b/src/java/org/apache/ddlutils/platform/mssql/MSSqlBuilder.java
@@ -1,588 +1,588 @@
package org.apache.ddlutils.platform.mssql;
/*
* Copyright 1999-2006 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.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.alteration.AddColumnChange;
import org.apache.ddlutils.alteration.AddPrimaryKeyChange;
import org.apache.ddlutils.alteration.ColumnAutoIncrementChange;
import org.apache.ddlutils.alteration.ColumnChange;
import org.apache.ddlutils.alteration.PrimaryKeyChange;
import org.apache.ddlutils.alteration.RemoveColumnChange;
import org.apache.ddlutils.alteration.RemovePrimaryKeyChange;
import org.apache.ddlutils.alteration.TableChange;
import org.apache.ddlutils.model.Column;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.ForeignKey;
import org.apache.ddlutils.model.Index;
import org.apache.ddlutils.model.Table;
import org.apache.ddlutils.platform.CreationParameters;
import org.apache.ddlutils.platform.SqlBuilder;
import org.apache.ddlutils.util.Jdbc3Utils;
/**
* The SQL Builder for the Microsoft SQL Server.
*
* @author James Strachan
* @author Thomas Dudziak
* @version $Revision$
*/
public class MSSqlBuilder extends SqlBuilder
{
/**
* Creates a new builder instance.
*
* @param platform The plaftform this builder belongs to
*/
public MSSqlBuilder(Platform platform)
{
super(platform);
addEscapedCharSequence("'", "''");
}
/**
* {@inheritDoc}
*/
public void createTable(Database database, Table table, Map parameters) throws IOException
{
writeQuotationOnStatement();
super.createTable(database, table, parameters);
}
/**
* {@inheritDoc}
*/
protected void alterTable(Database currentModel, Table currentTable, Database desiredModel, Table desiredTable, boolean doDrops, boolean modifyColumns) throws IOException
{
// we only want to generate the quotation start statement if there is something to write
// thus we write the alteration commands into a temporary writer
// and only if something was written, write the quotation start statement and the
// alteration commands to the original writer
Writer originalWriter = getWriter();
StringWriter tempWriter = new StringWriter();
setWriter(tempWriter);
super.alterTable(currentModel, currentTable, desiredModel, desiredTable, doDrops, modifyColumns);
setWriter(originalWriter);
String alterationCommands = tempWriter.toString();
if (alterationCommands.trim().length() > 0)
{
writeQuotationOnStatement();
getWriter().write(alterationCommands);
}
}
/**
* {@inheritDoc}
*/
public void dropTable(Table table) throws IOException
{
String tableName = getTableName(table);
writeQuotationOnStatement();
print("IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = ");
printAlwaysSingleQuotedIdentifier(tableName);
println(")");
println("BEGIN");
println(" DECLARE @tablename nvarchar(256), @constraintname nvarchar(256)");
println(" DECLARE refcursor CURSOR FOR");
println(" SELECT object_name(objs.parent_obj) tablename, objs.name constraintname");
println(" FROM sysobjects objs JOIN sysconstraints cons ON objs.id = cons.constid");
print(" WHERE objs.xtype != 'PK' AND object_name(objs.parent_obj) = ");
printAlwaysSingleQuotedIdentifier(tableName);
println(" OPEN refcursor");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" WHILE @@FETCH_STATUS = 0");
println(" BEGIN");
println(" EXEC ('ALTER TABLE '+@tablename+' DROP CONSTRAINT '+@constraintname)");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" END");
println(" CLOSE refcursor");
println(" DEALLOCATE refcursor");
print(" DROP TABLE ");
printlnIdentifier(tableName);
print("END");
printEndOfStatement();
}
/**
* {@inheritDoc}
*/
public void dropExternalForeignKeys(Table table) throws IOException
{
writeQuotationOnStatement();
super.dropExternalForeignKeys(table);
}
/**
* {@inheritDoc}
*/
protected String getNativeDefaultValue(Column column)
{
// Sql Server wants BIT default values as 0 or 1
if ((column.getTypeCode() == Types.BIT) ||
(Jdbc3Utils.supportsJava14JdbcTypes() && (column.getTypeCode() == Jdbc3Utils.determineBooleanTypeCode())))
{
return getDefaultValueHelper().convert(column.getDefaultValue(), column.getTypeCode(), Types.SMALLINT).toString();
}
else
{
return super.getNativeDefaultValue(column);
}
}
/**
* {@inheritDoc}
*/
protected void writeColumnAutoIncrementStmt(Table table, Column column) throws IOException
{
print("IDENTITY (1,1) ");
}
/**
* {@inheritDoc}
*/
public void writeExternalIndexDropStmt(Table table, Index index) throws IOException
{
print("DROP INDEX ");
printIdentifier(getTableName(table));
print(".");
printIdentifier(getIndexName(index));
printEndOfStatement();
}
/**
* {@inheritDoc}
*/
public void writeColumnAlterStmt(Table table, Column column, boolean isNewColumn) throws IOException
{
writeTableAlterStmt(table);
print(isNewColumn ? "ADD " : "ALTER COLUMN ");
writeColumn(table, column);
printEndOfStatement();
}
/**
* {@inheritDoc}
*/
protected void writeExternalForeignKeyDropStmt(Table table, ForeignKey foreignKey) throws IOException
{
String constraintName = getForeignKeyName(table, foreignKey);
print("IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'F' AND name = ");
printAlwaysSingleQuotedIdentifier(constraintName);
println(")");
printIndent();
print("ALTER TABLE ");
printIdentifier(getTableName(table));
print(" DROP CONSTRAINT ");
printIdentifier(constraintName);
printEndOfStatement();
}
/**
* Writes the statement that turns on the ability to write delimited identifiers.
*/
private void writeQuotationOnStatement() throws IOException
{
if (getPlatform().isDelimitedIdentifierModeOn())
{
print("SET quoted_identifier on");
printEndOfStatement();
}
}
/**
* {@inheritDoc}
*/
public String getSelectLastIdentityValues(Table table)
{
return "SELECT @@IDENTITY";
}
/**
* {@inheritDoc}
*/
public String getDeleteSql(Table table, Map pkValues, boolean genPlaceholders)
{
return getQuotationOnStatement() + super.getDeleteSql(table, pkValues, genPlaceholders);
}
/**
* {@inheritDoc}
*/
public String getInsertSql(Table table, Map columnValues, boolean genPlaceholders)
{
return getQuotationOnStatement() + super.getInsertSql(table, columnValues, genPlaceholders);
}
/**
* {@inheritDoc}
*/
public String getUpdateSql(Table table, Map columnValues, boolean genPlaceholders)
{
return getQuotationOnStatement() + super.getUpdateSql(table, columnValues, genPlaceholders);
}
/**
* Returns the statement that turns on the ability to write delimited identifiers.
*
* @return The quotation-on statement
*/
private String getQuotationOnStatement()
{
if (getPlatform().isDelimitedIdentifierModeOn())
{
return "SET quoted_identifier on" + getPlatformInfo().getSqlCommandDelimiter() + "\n";
}
else
{
return "";
}
}
/**
* Prints the given identifier with enforced single quotes around it regardless of whether
* delimited identifiers are turned on or not.
*
* @param identifier The identifier
*/
private void printAlwaysSingleQuotedIdentifier(String identifier) throws IOException
{
print("'");
print(identifier);
print("'");
}
/**
* {@inheritDoc}
*/
protected void writeCopyDataStatement(Table sourceTable, Table targetTable) throws IOException
{
// Sql Server per default does not allow us to insert values explicitly into
// identity columns. However, we can change this behavior
boolean hasIdentityColumns = targetTable.getAutoIncrementColumns().length > 0;
if (hasIdentityColumns)
{
print("SET IDENTITY_INSERT ");
printIdentifier(getTableName(targetTable));
print(" ON");
printEndOfStatement();
}
super.writeCopyDataStatement(sourceTable, targetTable);
// We have to turn it off ASAP because it can be on only for one table per session
if (hasIdentityColumns)
{
print("SET IDENTITY_INSERT ");
printIdentifier(getTableName(targetTable));
print(" OFF");
printEndOfStatement();
}
}
/**
* {@inheritDoc}
*/
protected void processChanges(Database currentModel, Database desiredModel, List changes, CreationParameters params) throws IOException
{
if (!changes.isEmpty())
{
writeQuotationOnStatement();
}
super.processChanges(currentModel, desiredModel, changes, params);
}
/**
* {@inheritDoc}
*/
protected void processTableStructureChanges(Database currentModel,
Database desiredModel,
Table sourceTable,
Table targetTable,
Map parameters,
List changes) throws IOException
{
// First we drop primary keys as necessary
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof RemovePrimaryKeyChange)
{
processChange(currentModel, desiredModel, (RemovePrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
RemovePrimaryKeyChange removePkChange = new RemovePrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getOldPrimaryKeyColumns());
processChange(currentModel, desiredModel, removePkChange);
removePkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
ArrayList columnChanges = new ArrayList();
// Next we add/remove columns
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddColumnChange)
{
AddColumnChange addColumnChange = (AddColumnChange)change;
- // Oracle can only add not insert columns
+ // Sql Server can only add not insert columns
if (addColumnChange.isAtEnd())
{
processChange(currentModel, desiredModel, addColumnChange);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
else if (change instanceof RemoveColumnChange)
{
processChange(currentModel, desiredModel, (RemoveColumnChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof ColumnAutoIncrementChange)
{
// Sql Server has no way of adding or removing a IDENTITY constraint
// Thus we have to rebuild the table anyway and can ignore all the other
// column changes
columnChanges = null;
}
else if ((change instanceof ColumnChange) && (columnChanges != null))
{
// we gather all changed columns because we can use the ALTER TABLE ALTER COLUMN
// statement for them
columnChanges.add(change);
}
}
if (columnChanges != null)
{
HashSet processedColumns = new HashSet();
for (Iterator changeIt = columnChanges.iterator(); changeIt.hasNext();)
{
ColumnChange change = (ColumnChange)changeIt.next();
Column sourceColumn = change.getChangedColumn();
Column targetColumn = targetTable.findColumn(sourceColumn.getName(), getPlatform().isDelimitedIdentifierModeOn());
if (!processedColumns.contains(targetColumn))
{
processColumnChange(sourceTable, targetTable, sourceColumn, targetColumn);
processedColumns.add(targetColumn);
}
changes.remove(change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
// Finally we add primary keys
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddPrimaryKeyChange)
{
processChange(currentModel, desiredModel, (AddPrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
AddPrimaryKeyChange addPkChange = new AddPrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getNewPrimaryKeyColumns());
processChange(currentModel, desiredModel, addPkChange);
addPkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
}
/**
* Processes the addition of a column to a table.
*
* @param currentModel The current database schema
* @param desiredModel The desired database schema
* @param change The change object
*/
protected void processChange(Database currentModel,
Database desiredModel,
AddColumnChange change) throws IOException
{
print("ALTER TABLE ");
printlnIdentifier(getTableName(change.getChangedTable()));
printIndent();
print("ADD ");
writeColumn(change.getChangedTable(), change.getNewColumn());
printEndOfStatement();
}
/**
* Processes the removal of a column from a table.
*
* @param currentModel The current database schema
* @param desiredModel The desired database schema
* @param change The change object
*/
protected void processChange(Database currentModel,
Database desiredModel,
RemoveColumnChange change) throws IOException
{
print("ALTER TABLE ");
printlnIdentifier(getTableName(change.getChangedTable()));
printIndent();
print("DROP COLUMN ");
printIdentifier(getColumnName(change.getColumn()));
printEndOfStatement();
}
/**
* Processes the removal of a primary key from a table.
*
* @param currentModel The current database schema
* @param desiredModel The desired database schema
* @param change The change object
*/
protected void processChange(Database currentModel,
Database desiredModel,
RemovePrimaryKeyChange change) throws IOException
{
// TODO: this would be easier when named primary keys are supported
// because then we can use ALTER TABLE DROP
String tableName = getTableName(change.getChangedTable());
println("BEGIN");
println(" DECLARE @tablename nvarchar(256), @constraintname nvarchar(256)");
println(" DECLARE refcursor CURSOR FOR");
println(" SELECT object_name(objs.parent_obj) tablename, objs.name constraintname");
println(" FROM sysobjects objs JOIN sysconstraints cons ON objs.id = cons.constid");
print(" WHERE objs.xtype = 'PK' AND object_name(objs.parent_obj) = ");
printAlwaysSingleQuotedIdentifier(tableName);
println(" OPEN refcursor");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" WHILE @@FETCH_STATUS = 0");
println(" BEGIN");
println(" EXEC ('ALTER TABLE '+@tablename+' DROP CONSTRAINT '+@constraintname)");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" END");
println(" CLOSE refcursor");
println(" DEALLOCATE refcursor");
print("END");
printEndOfStatement();
}
/**
* Processes a change to a column.
*
* @param sourceTable The current table
* @param targetTable The desired table
* @param sourceColumn The current column
* @param targetColumn The desired column
*/
protected void processColumnChange(Table sourceTable,
Table targetTable,
Column sourceColumn,
Column targetColumn) throws IOException
{
boolean hasDefault = sourceColumn.getParsedDefaultValue() != null;
boolean shallHaveDefault = targetColumn.getParsedDefaultValue() != null;
String newDefault = targetColumn.getDefaultValue();
// Sql Server does not like it if there is a default spec in the ALTER TABLE ALTER COLUMN
// statement; thus we have to change the default manually
if (newDefault != null)
{
targetColumn.setDefaultValue(null);
}
if (hasDefault)
{
// we're dropping the old default
String tableName = getTableName(sourceTable);
String columnName = getColumnName(sourceColumn);
println("BEGIN");
println(" DECLARE @tablename nvarchar(256), @constraintname nvarchar(256)");
println(" DECLARE refcursor CURSOR FOR");
println(" SELECT object_name(objs.parent_obj) tablename, objs.name constraintname");
println(" FROM sysobjects objs JOIN sysconstraints cons ON objs.id = cons.constid");
println(" WHERE objs.xtype = 'D' AND");
print(" cons.colid = (SELECT colid FROM syscolumns WHERE id = object_id(");
printAlwaysSingleQuotedIdentifier(tableName);
print(") AND name = ");
printAlwaysSingleQuotedIdentifier(columnName);
println(") AND");
print(" object_name(objs.parent_obj) = ");
printAlwaysSingleQuotedIdentifier(tableName);
println(" OPEN refcursor");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" WHILE @@FETCH_STATUS = 0");
println(" BEGIN");
println(" EXEC ('ALTER TABLE '+@tablename+' DROP CONSTRAINT '+@constraintname)");
println(" FETCH NEXT FROM refcursor INTO @tablename, @constraintname");
println(" END");
println(" CLOSE refcursor");
println(" DEALLOCATE refcursor");
print("END");
printEndOfStatement();
}
print("ALTER TABLE ");
printlnIdentifier(getTableName(sourceTable));
printIndent();
print("ALTER COLUMN ");
writeColumn(sourceTable, targetColumn);
printEndOfStatement();
if (shallHaveDefault)
{
targetColumn.setDefaultValue(newDefault);
// if the column shall have a default, then we have to add it as a constraint
print("ALTER TABLE ");
printlnIdentifier(getTableName(sourceTable));
printIndent();
print("ADD CONSTRAINT ");
printIdentifier(getConstraintName("DF", sourceTable, sourceColumn.getName(), null));
writeColumnDefaultValueStmt(sourceTable, targetColumn);
print(" FOR ");
printIdentifier(getColumnName(sourceColumn));
printEndOfStatement();
}
}
}
| true | true | protected void processTableStructureChanges(Database currentModel,
Database desiredModel,
Table sourceTable,
Table targetTable,
Map parameters,
List changes) throws IOException
{
// First we drop primary keys as necessary
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof RemovePrimaryKeyChange)
{
processChange(currentModel, desiredModel, (RemovePrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
RemovePrimaryKeyChange removePkChange = new RemovePrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getOldPrimaryKeyColumns());
processChange(currentModel, desiredModel, removePkChange);
removePkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
ArrayList columnChanges = new ArrayList();
// Next we add/remove columns
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddColumnChange)
{
AddColumnChange addColumnChange = (AddColumnChange)change;
// Oracle can only add not insert columns
if (addColumnChange.isAtEnd())
{
processChange(currentModel, desiredModel, addColumnChange);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
else if (change instanceof RemoveColumnChange)
{
processChange(currentModel, desiredModel, (RemoveColumnChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof ColumnAutoIncrementChange)
{
// Sql Server has no way of adding or removing a IDENTITY constraint
// Thus we have to rebuild the table anyway and can ignore all the other
// column changes
columnChanges = null;
}
else if ((change instanceof ColumnChange) && (columnChanges != null))
{
// we gather all changed columns because we can use the ALTER TABLE ALTER COLUMN
// statement for them
columnChanges.add(change);
}
}
if (columnChanges != null)
{
HashSet processedColumns = new HashSet();
for (Iterator changeIt = columnChanges.iterator(); changeIt.hasNext();)
{
ColumnChange change = (ColumnChange)changeIt.next();
Column sourceColumn = change.getChangedColumn();
Column targetColumn = targetTable.findColumn(sourceColumn.getName(), getPlatform().isDelimitedIdentifierModeOn());
if (!processedColumns.contains(targetColumn))
{
processColumnChange(sourceTable, targetTable, sourceColumn, targetColumn);
processedColumns.add(targetColumn);
}
changes.remove(change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
// Finally we add primary keys
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddPrimaryKeyChange)
{
processChange(currentModel, desiredModel, (AddPrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
AddPrimaryKeyChange addPkChange = new AddPrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getNewPrimaryKeyColumns());
processChange(currentModel, desiredModel, addPkChange);
addPkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
}
| protected void processTableStructureChanges(Database currentModel,
Database desiredModel,
Table sourceTable,
Table targetTable,
Map parameters,
List changes) throws IOException
{
// First we drop primary keys as necessary
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof RemovePrimaryKeyChange)
{
processChange(currentModel, desiredModel, (RemovePrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
RemovePrimaryKeyChange removePkChange = new RemovePrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getOldPrimaryKeyColumns());
processChange(currentModel, desiredModel, removePkChange);
removePkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
ArrayList columnChanges = new ArrayList();
// Next we add/remove columns
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddColumnChange)
{
AddColumnChange addColumnChange = (AddColumnChange)change;
// Sql Server can only add not insert columns
if (addColumnChange.isAtEnd())
{
processChange(currentModel, desiredModel, addColumnChange);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
else if (change instanceof RemoveColumnChange)
{
processChange(currentModel, desiredModel, (RemoveColumnChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof ColumnAutoIncrementChange)
{
// Sql Server has no way of adding or removing a IDENTITY constraint
// Thus we have to rebuild the table anyway and can ignore all the other
// column changes
columnChanges = null;
}
else if ((change instanceof ColumnChange) && (columnChanges != null))
{
// we gather all changed columns because we can use the ALTER TABLE ALTER COLUMN
// statement for them
columnChanges.add(change);
}
}
if (columnChanges != null)
{
HashSet processedColumns = new HashSet();
for (Iterator changeIt = columnChanges.iterator(); changeIt.hasNext();)
{
ColumnChange change = (ColumnChange)changeIt.next();
Column sourceColumn = change.getChangedColumn();
Column targetColumn = targetTable.findColumn(sourceColumn.getName(), getPlatform().isDelimitedIdentifierModeOn());
if (!processedColumns.contains(targetColumn))
{
processColumnChange(sourceTable, targetTable, sourceColumn, targetColumn);
processedColumns.add(targetColumn);
}
changes.remove(change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
}
}
// Finally we add primary keys
for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
{
TableChange change = (TableChange)changeIt.next();
if (change instanceof AddPrimaryKeyChange)
{
processChange(currentModel, desiredModel, (AddPrimaryKeyChange)change);
change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
else if (change instanceof PrimaryKeyChange)
{
PrimaryKeyChange pkChange = (PrimaryKeyChange)change;
AddPrimaryKeyChange addPkChange = new AddPrimaryKeyChange(pkChange.getChangedTable(),
pkChange.getNewPrimaryKeyColumns());
processChange(currentModel, desiredModel, addPkChange);
addPkChange.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
changeIt.remove();
}
}
}
|
diff --git a/storyline/src/app/xzone/storyline/component/DateTimePicker.java b/storyline/src/app/xzone/storyline/component/DateTimePicker.java
index 5ce8b3e..0498369 100644
--- a/storyline/src/app/xzone/storyline/component/DateTimePicker.java
+++ b/storyline/src/app/xzone/storyline/component/DateTimePicker.java
@@ -1,66 +1,66 @@
package app.xzone.storyline.component;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import app.xzone.storyline.util.TimeUtil;
public class DateTimePicker {
// Component for handle date picker
public static void showDatePicker(final Context context,
final View resourceTarget) {
DateTime dt = new DateTime();
DatePickerDialog dp = null;
dp = new DatePickerDialog(context, new OnDateSetListener() {
@Override
public void onDateSet(android.widget.DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
DateTimeFormatter fmt = DateTimeFormat
- .forPattern("MMM dd, yyyy");
+ .forPattern("E MMM dd, yyyy");
TextView dateText = (TextView) resourceTarget;
dateText.setText((new DateTime(year, monthOfYear+1,
dayOfMonth, 0, 0, 0, 0)).toString(fmt));
}
}, dt.getYear(), dt.getMonthOfYear()-1, dt.getDayOfMonth());
dp.show();
}
// Component for handle time picker
public static void showTimePicker(final Context context,
final View resourceTarget) {
DateTime dt = new DateTime();
TimePickerDialog tp = null;
tp = new TimePickerDialog(context, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView timeText = (TextView) resourceTarget;
timeText.setText(hourOfDay + ":" + minute
+ TimeUtil.timeArea(hourOfDay));
}
}, dt.getHourOfDay(), dt.getMinuteOfHour(), true);
tp.show();
}
}
| true | true | public static void showDatePicker(final Context context,
final View resourceTarget) {
DateTime dt = new DateTime();
DatePickerDialog dp = null;
dp = new DatePickerDialog(context, new OnDateSetListener() {
@Override
public void onDateSet(android.widget.DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
DateTimeFormatter fmt = DateTimeFormat
.forPattern("MMM dd, yyyy");
TextView dateText = (TextView) resourceTarget;
dateText.setText((new DateTime(year, monthOfYear+1,
dayOfMonth, 0, 0, 0, 0)).toString(fmt));
}
}, dt.getYear(), dt.getMonthOfYear()-1, dt.getDayOfMonth());
dp.show();
}
| public static void showDatePicker(final Context context,
final View resourceTarget) {
DateTime dt = new DateTime();
DatePickerDialog dp = null;
dp = new DatePickerDialog(context, new OnDateSetListener() {
@Override
public void onDateSet(android.widget.DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
DateTimeFormatter fmt = DateTimeFormat
.forPattern("E MMM dd, yyyy");
TextView dateText = (TextView) resourceTarget;
dateText.setText((new DateTime(year, monthOfYear+1,
dayOfMonth, 0, 0, 0, 0)).toString(fmt));
}
}, dt.getYear(), dt.getMonthOfYear()-1, dt.getDayOfMonth());
dp.show();
}
|
diff --git a/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java b/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java
index 9a0d7b297..fbff72dd8 100644
--- a/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java
+++ b/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java
@@ -1,326 +1,326 @@
/*
* 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.pdfbox.tools;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.exceptions.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.util.ImageIOUtil;
/**
* Convert a PDF document to an image.
*
* @author <a href="[email protected]">Ben Litchfield</a>
* @version $Revision: 1.6 $
*/
public class PDFToImage
{
private static final String PASSWORD = "-password";
private static final String START_PAGE = "-startPage";
private static final String END_PAGE = "-endPage";
private static final String IMAGE_FORMAT = "-imageType";
private static final String OUTPUT_PREFIX = "-outputPrefix";
private static final String COLOR = "-color";
private static final String RESOLUTION = "-resolution";
private static final String CROPBOX = "-cropbox";
private static final String NONSEQ = "-nonSeq";
/**
* private constructor.
*/
private PDFToImage()
{
//static class
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be one and a reference to a file.
*
* @throws Exception If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException, CryptographyException
{
boolean useNonSeqParser = false;
String password = "";
String pdfFile = null;
String outputPrefix = null;
String imageFormat = "jpg";
int startPage = 1;
int endPage = Integer.MAX_VALUE;
String color = "rgb";
int dpi;
float cropBoxLowerLeftX = 0;
float cropBoxLowerLeftY = 0;
float cropBoxUpperRightX = 0;
float cropBoxUpperRightY = 0;
try
{
dpi = Toolkit.getDefaultToolkit().getScreenResolution();
}
catch( HeadlessException e )
{
dpi = 96;
}
for( int i = 0; i < args.length; i++ )
{
if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( args[i].equals( START_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
startPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( END_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
endPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( IMAGE_FORMAT ) )
{
i++;
imageFormat = args[i];
}
else if( args[i].equals( OUTPUT_PREFIX ) )
{
i++;
outputPrefix = args[i];
}
else if( args[i].equals( COLOR ) )
{
i++;
color = args[i];
}
else if( args[i].equals( RESOLUTION ) )
{
i++;
dpi = Integer.parseInt(args[i]);
}
else if( args[i].equals( CROPBOX ) )
{
i++;
cropBoxLowerLeftX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxLowerLeftY = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightY = Float.valueOf(args[i]).floatValue();
}
else if( args[i].equals( NONSEQ ) )
{
useNonSeqParser = true;
}
else
{
if( pdfFile == null )
{
pdfFile = args[i];
}
}
}
if( pdfFile == null )
{
usage();
}
else
{
if(outputPrefix == null)
{
outputPrefix = pdfFile.substring( 0, pdfFile.lastIndexOf( '.' ));
}
PDDocument document = null;
try
{
if (useNonSeqParser)
{
document = PDDocument.loadNonSeq(new File(pdfFile), null, password);
}
else
{
document = PDDocument.load( pdfFile );
if( document.isEncrypted() )
{
try
{
document.decrypt( password );
}
catch( InvalidPasswordException e )
{
if( args.length == 4 )//they supplied the wrong password
{
System.err.println( "Error: The supplied password is incorrect." );
System.exit( 2 );
}
else
{
//they didn't supply a password and the default of "" was wrong.
System.err.println( "Error: The document is encrypted." );
usage();
}
}
}
}
int imageType = 24;
if ("bilevel".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_BINARY;
}
else if ("indexed".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_INDEXED;
}
else if ("gray".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_GRAY;
}
else if ("rgb".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_RGB;
}
else if ("rgba".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_ARGB;
}
else
{
System.err.println( "Error: the number of bits per pixel must be 1, 8 or 24." );
System.exit( 2 );
}
//if a CropBox has been specified, update the CropBox:
//changeCropBoxes(PDDocument document,float a, float b, float c,float d)
if ( cropBoxLowerLeftX!=0 || cropBoxLowerLeftY!=0
|| cropBoxUpperRightX!=0 || cropBoxUpperRightY!=0 )
{
changeCropBoxes(document,
cropBoxLowerLeftX, cropBoxLowerLeftY,
cropBoxUpperRightX, cropBoxUpperRightY);
}
// render the pages
boolean success = true;
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = startPage - 1; i < endPage && i < numPages; i++)
{
- BufferedImage image = renderer.renderImage(i, dpi);
+ BufferedImage image = renderer.renderImageWithDPI(i, dpi);
String fileName = outputPrefix + (i + 1);
- success &= ImageIOUtil.writeImage(image, imageFormat, fileName, imageType, dpi);
+ success &= ImageIOUtil.writeImage(image, imageFormat, fileName, imageType);
}
if (!success)
{
System.err.println( "Error: no writer found for image format '"
+ imageFormat + "'" );
System.exit(1);
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
/**
* This will print the usage requirements and exit.
*/
private static void usage()
{
System.err.println( "Usage: java -jar pdfbox-app-x.y.z.jar PDFToImage [OPTIONS] <PDF file>\n" +
" -password <password> Password to decrypt document\n" +
" -imageType <image type> (" + getImageFormats() + ")\n" +
" -outputPrefix <output prefix> Filename prefix for image files\n" +
" -startPage <number> The first page to start extraction(1 based)\n" +
" -endPage <number> The last page to extract(inclusive)\n" +
" -color <string> The color depth (valid: bilevel, indexed, gray, rgb, rgba)\n" +
" -resolution <number> The bitmap resolution in dpi\n" +
" -cropbox <number> <number> <number> <number> The page area to export\n" +
" -nonSeq Enables the new non-sequential parser\n" +
" <PDF file> The PDF document to use\n"
);
System.exit( 1 );
}
private static String getImageFormats()
{
StringBuffer retval = new StringBuffer();
String[] formats = ImageIO.getReaderFormatNames();
for( int i = 0; i < formats.length; i++ )
{
retval.append( formats[i] );
if( i + 1 < formats.length )
{
retval.append( "," );
}
}
return retval.toString();
}
private static void changeCropBoxes(PDDocument document,float a, float b, float c,float d)
{
List pages = document.getDocumentCatalog().getAllPages();
for( int i = 0; i < pages.size(); i++ )
{
System.out.println("resizing page");
PDPage page = (PDPage)pages.get( i );
PDRectangle rectangle = new PDRectangle();
rectangle.setLowerLeftX(a);
rectangle.setLowerLeftY(b);
rectangle.setUpperRightX(c);
rectangle.setUpperRightY(d);
page.setMediaBox(rectangle);
page.setCropBox(rectangle);
}
}
}
| false | true | public static void main( String[] args ) throws IOException, CryptographyException
{
boolean useNonSeqParser = false;
String password = "";
String pdfFile = null;
String outputPrefix = null;
String imageFormat = "jpg";
int startPage = 1;
int endPage = Integer.MAX_VALUE;
String color = "rgb";
int dpi;
float cropBoxLowerLeftX = 0;
float cropBoxLowerLeftY = 0;
float cropBoxUpperRightX = 0;
float cropBoxUpperRightY = 0;
try
{
dpi = Toolkit.getDefaultToolkit().getScreenResolution();
}
catch( HeadlessException e )
{
dpi = 96;
}
for( int i = 0; i < args.length; i++ )
{
if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( args[i].equals( START_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
startPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( END_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
endPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( IMAGE_FORMAT ) )
{
i++;
imageFormat = args[i];
}
else if( args[i].equals( OUTPUT_PREFIX ) )
{
i++;
outputPrefix = args[i];
}
else if( args[i].equals( COLOR ) )
{
i++;
color = args[i];
}
else if( args[i].equals( RESOLUTION ) )
{
i++;
dpi = Integer.parseInt(args[i]);
}
else if( args[i].equals( CROPBOX ) )
{
i++;
cropBoxLowerLeftX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxLowerLeftY = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightY = Float.valueOf(args[i]).floatValue();
}
else if( args[i].equals( NONSEQ ) )
{
useNonSeqParser = true;
}
else
{
if( pdfFile == null )
{
pdfFile = args[i];
}
}
}
if( pdfFile == null )
{
usage();
}
else
{
if(outputPrefix == null)
{
outputPrefix = pdfFile.substring( 0, pdfFile.lastIndexOf( '.' ));
}
PDDocument document = null;
try
{
if (useNonSeqParser)
{
document = PDDocument.loadNonSeq(new File(pdfFile), null, password);
}
else
{
document = PDDocument.load( pdfFile );
if( document.isEncrypted() )
{
try
{
document.decrypt( password );
}
catch( InvalidPasswordException e )
{
if( args.length == 4 )//they supplied the wrong password
{
System.err.println( "Error: The supplied password is incorrect." );
System.exit( 2 );
}
else
{
//they didn't supply a password and the default of "" was wrong.
System.err.println( "Error: The document is encrypted." );
usage();
}
}
}
}
int imageType = 24;
if ("bilevel".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_BINARY;
}
else if ("indexed".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_INDEXED;
}
else if ("gray".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_GRAY;
}
else if ("rgb".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_RGB;
}
else if ("rgba".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_ARGB;
}
else
{
System.err.println( "Error: the number of bits per pixel must be 1, 8 or 24." );
System.exit( 2 );
}
//if a CropBox has been specified, update the CropBox:
//changeCropBoxes(PDDocument document,float a, float b, float c,float d)
if ( cropBoxLowerLeftX!=0 || cropBoxLowerLeftY!=0
|| cropBoxUpperRightX!=0 || cropBoxUpperRightY!=0 )
{
changeCropBoxes(document,
cropBoxLowerLeftX, cropBoxLowerLeftY,
cropBoxUpperRightX, cropBoxUpperRightY);
}
// render the pages
boolean success = true;
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = startPage - 1; i < endPage && i < numPages; i++)
{
BufferedImage image = renderer.renderImage(i, dpi);
String fileName = outputPrefix + (i + 1);
success &= ImageIOUtil.writeImage(image, imageFormat, fileName, imageType, dpi);
}
if (!success)
{
System.err.println( "Error: no writer found for image format '"
+ imageFormat + "'" );
System.exit(1);
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
| public static void main( String[] args ) throws IOException, CryptographyException
{
boolean useNonSeqParser = false;
String password = "";
String pdfFile = null;
String outputPrefix = null;
String imageFormat = "jpg";
int startPage = 1;
int endPage = Integer.MAX_VALUE;
String color = "rgb";
int dpi;
float cropBoxLowerLeftX = 0;
float cropBoxLowerLeftY = 0;
float cropBoxUpperRightX = 0;
float cropBoxUpperRightY = 0;
try
{
dpi = Toolkit.getDefaultToolkit().getScreenResolution();
}
catch( HeadlessException e )
{
dpi = 96;
}
for( int i = 0; i < args.length; i++ )
{
if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
else if( args[i].equals( START_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
startPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( END_PAGE ) )
{
i++;
if( i >= args.length )
{
usage();
}
endPage = Integer.parseInt( args[i] );
}
else if( args[i].equals( IMAGE_FORMAT ) )
{
i++;
imageFormat = args[i];
}
else if( args[i].equals( OUTPUT_PREFIX ) )
{
i++;
outputPrefix = args[i];
}
else if( args[i].equals( COLOR ) )
{
i++;
color = args[i];
}
else if( args[i].equals( RESOLUTION ) )
{
i++;
dpi = Integer.parseInt(args[i]);
}
else if( args[i].equals( CROPBOX ) )
{
i++;
cropBoxLowerLeftX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxLowerLeftY = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightX = Float.valueOf(args[i]).floatValue();
i++;
cropBoxUpperRightY = Float.valueOf(args[i]).floatValue();
}
else if( args[i].equals( NONSEQ ) )
{
useNonSeqParser = true;
}
else
{
if( pdfFile == null )
{
pdfFile = args[i];
}
}
}
if( pdfFile == null )
{
usage();
}
else
{
if(outputPrefix == null)
{
outputPrefix = pdfFile.substring( 0, pdfFile.lastIndexOf( '.' ));
}
PDDocument document = null;
try
{
if (useNonSeqParser)
{
document = PDDocument.loadNonSeq(new File(pdfFile), null, password);
}
else
{
document = PDDocument.load( pdfFile );
if( document.isEncrypted() )
{
try
{
document.decrypt( password );
}
catch( InvalidPasswordException e )
{
if( args.length == 4 )//they supplied the wrong password
{
System.err.println( "Error: The supplied password is incorrect." );
System.exit( 2 );
}
else
{
//they didn't supply a password and the default of "" was wrong.
System.err.println( "Error: The document is encrypted." );
usage();
}
}
}
}
int imageType = 24;
if ("bilevel".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_BINARY;
}
else if ("indexed".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_INDEXED;
}
else if ("gray".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_BYTE_GRAY;
}
else if ("rgb".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_RGB;
}
else if ("rgba".equalsIgnoreCase(color))
{
imageType = BufferedImage.TYPE_INT_ARGB;
}
else
{
System.err.println( "Error: the number of bits per pixel must be 1, 8 or 24." );
System.exit( 2 );
}
//if a CropBox has been specified, update the CropBox:
//changeCropBoxes(PDDocument document,float a, float b, float c,float d)
if ( cropBoxLowerLeftX!=0 || cropBoxLowerLeftY!=0
|| cropBoxUpperRightX!=0 || cropBoxUpperRightY!=0 )
{
changeCropBoxes(document,
cropBoxLowerLeftX, cropBoxLowerLeftY,
cropBoxUpperRightX, cropBoxUpperRightY);
}
// render the pages
boolean success = true;
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = startPage - 1; i < endPage && i < numPages; i++)
{
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
String fileName = outputPrefix + (i + 1);
success &= ImageIOUtil.writeImage(image, imageFormat, fileName, imageType);
}
if (!success)
{
System.err.println( "Error: no writer found for image format '"
+ imageFormat + "'" );
System.exit(1);
}
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
|
diff --git a/src/org/ow2/proactive_grid_cloud_portal/scheduler/client/Task.java b/src/org/ow2/proactive_grid_cloud_portal/scheduler/client/Task.java
index d00bcea..7dcf25d 100644
--- a/src/org/ow2/proactive_grid_cloud_portal/scheduler/client/Task.java
+++ b/src/org/ow2/proactive_grid_cloud_portal/scheduler/client/Task.java
@@ -1,339 +1,338 @@
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive_grid_cloud_portal.scheduler.client;
import java.io.Serializable;
import java.util.Date;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
/**
* A representation for the business object corresponding to a Task.
* @author ahagea
*
*/
@SuppressWarnings("serial")
public class Task implements Serializable, Comparable<Task> {
private long id;
private String name;
private String hostName;
private TaskStatus status;
private long startTime;
private long finishedTime;
private long executionDuration;
private String description;
private int maxNumberOfExec;
private int numberOfExecLeft;
private int maxNumberOfExecOnFailure;
private int numberOfExecOnFailureLeft;
private int nodeCount;
/**
* The constructor that has no arguments required by the Serializable interface
*/
public Task() {
}
/**
* The constructor of the class that is used for creating new instances of the class.
* @param id the task id
* @param name the task name
* @param status the task status
* @param hostName the last execution HostName of the task
* @param startTime the start time of the task
* @param finishedTime the finished time of the task
* @param executionDuration the duration of the task execution in milliseconds
* @param description task description.
* @param nodeCount number of nodes used by the task
* @param maxNumberOfExec maximum number of executions
* @param numberOfExecLeft number of executions left
* @param maxNumberOfExecOnFailure maximum number of executions on failure
* @param maxNumberOfExecOnFailureLeft maximum number of executions on failure left
*/
public Task(long id, String name, TaskStatus status, String hostName, long startTime, long finishedTime,
long executionDuration, String description, int nodeCount, int maxNumberOfExec,
int numberOfExecLeft, int maxNumberOfExecOnFailure, int numberOfExecOnFailureLeft) {
this.id = id;
this.name = name;
this.status = status;
this.hostName = hostName;
this.startTime = startTime;
this.finishedTime = finishedTime;
this.executionDuration = executionDuration;
this.description = description;
this.nodeCount = nodeCount;
this.maxNumberOfExec = maxNumberOfExec;
this.numberOfExecLeft = numberOfExecLeft;
this.maxNumberOfExecOnFailure = maxNumberOfExecOnFailure;
this.numberOfExecOnFailureLeft = numberOfExecOnFailureLeft;
}
/**
* Setter of the task id.
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* Getter of the task id.
* @return the id
*/
public Long getId() {
return id;
}
/**
* Setter of the task name.
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter of the task name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Setter of the host name of the task.
* @param hostName the hostName to set
*/
public void setHostName(String hostName) {
this.hostName = hostName;
}
/**
* Getter of the hostname of the task.
* @return the hostName
*/
public String getHostName() {
return hostName;
}
/**
* Setter of the status of the task.
* @param status the status to set
*/
public void setStatus(TaskStatus status) {
this.status = status;
}
/**
* Getter of the status of the task.
* @return the status
*/
public TaskStatus getStatus() {
return status;
}
/**
* Setter of the start time of the task.
* @param startTime the startTime to set
*/
public void setStartTime(long startTime) {
this.startTime = startTime;
}
/**
* Getter of the start time of the task.
* @return the startTime
*/
public long getStartTime() {
return startTime;
}
/**
* Setter of the finished time of the task.
* @param finishedTime the finishTime to set
*/
public void setFinishTime(long finishedTime) {
this.finishedTime = finishedTime;
}
/**
* Getter of the finished time of the task.
* @return the finishTime
*/
public long getFinishTime() {
return finishedTime;
}
/**
* Setter of the execution time of the task.
* @param executionDuration the executionTime to set
*/
public void setExecutionTime(long executionDuration) {
this.executionDuration = executionDuration;
}
/**
* Getter of the execution time of the task.
* @return the executionTime
*/
public long getExecutionTime() {
return executionDuration;
}
public int getMaxNumberOfExec() {
return maxNumberOfExec;
}
public int getNumberOfExecLeft() {
return numberOfExecLeft;
}
public int getMaxNumberOfExecOnFailure() {
return maxNumberOfExecOnFailure;
}
public int getNumberOfExecOnFailureLeft() {
return numberOfExecOnFailureLeft;
}
public int getNodeCount() {
return this.nodeCount;
}
/**
* Setter for the task description.
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Getter of the task description.
* @return the description
*/
public String getDescription() {
return description;
}
public String getIdName() {
return "id";
}
public int compareTo(Task task) {
return ((Long) this.id).compareTo((Long) task.getId());
}
public String toString() {
return "[ id=" + id + "; " + "name=" + name + "; " + "status=" + status + "; " + "hostName=" +
hostName + "; " + "startTime=" + new Date(startTime) + "; " + "finishTime=" +
new Date(finishedTime) + "; " + "executionDuration=" + executionDuration + "; " + "description=" +
description + "]";
}
public boolean equals(Object o) {
if (!(o instanceof Task))
return false;
return this.id == ((Task) o).getId();
}
/**
* @param jsonTask the JSON representation of a Task
* @return the POJO equivalent
*/
public static Task parseJson(JSONObject jsonTask) {
String name = jsonTask.get("name").isString().stringValue();
JSONObject taskInfo = jsonTask.get("taskInfo").isObject();
String hostName = "";
if (taskInfo.containsKey("executionHostName")) {
JSONString host = taskInfo.get("executionHostName").isString();
if (host != null) {
hostName = host.stringValue();
}
}
long id = (long) taskInfo.get("taskId").isObject().get("id").isNumber().doubleValue();
String status = taskInfo.get("taskStatus").isString().stringValue();
long startTime = (long) taskInfo.get("startTime").isNumber().doubleValue();
long finishedTime = (long) taskInfo.get("finishedTime").isNumber().doubleValue();
long executionDuration = (long) taskInfo.get("executionDuration").isNumber().doubleValue();
String description = "";
if (jsonTask.containsKey("description")) {
JSONString desc = jsonTask.get("description").isString();
if (desc != null)
description = desc.stringValue();
}
- int maxExec = (int) jsonTask.get("maxNumberOfExecution").isObject().get("value").isObject().get(
- "value").isNumber().doubleValue();
+ int maxExec = (int) jsonTask.get("maxNumberOfExecution").isNumber().doubleValue();
int execLeft = (int) taskInfo.get("numberOfExecutionLeft").isNumber().doubleValue();
int execOnFailureLeft = (int) taskInfo.get("numberOfExecutionOnFailureLeft").isNumber().doubleValue();
int maxExecOnFailure = (int) jsonTask.get("maxNumberOfExecutionOnFailure").isNumber().doubleValue();
int nodes = 1;
if (jsonTask.containsKey("parallelEnvironment")) {
JSONObject parEnv = jsonTask.get("parallelEnvironment").isObject();
if (parEnv != null && parEnv.containsKey("nodesNumber")) {
nodes = (int) parEnv.get("nodesNumber").isNumber().doubleValue();
}
}
return new Task(id, name, TaskStatus.valueOf(status), hostName, startTime, finishedTime,
executionDuration, description, nodes, execLeft, maxExec, maxExecOnFailure, execOnFailureLeft);
}
/**
* @param task
* @return Return true if and only if all the task field
* are equal to those of <code>this</code>
*/
public boolean isEquals(Task task) {
return this.id == task.getId() && this.name.equals(task.getName()) &&
this.status.equals(task.getStatus()) && this.hostName.equals(task.getHostName()) &&
this.startTime == task.getStartTime() && this.finishedTime == task.getFinishTime() &&
this.executionDuration == task.getExecutionTime() && this.description.equals(task.description);
}
public boolean isEqual(Task t) {
return this.id == t.getId() && this.name.equals(t.getName()) &&
this.hostName.equals(t.getHostName()) && this.status == t.getStatus() &&
this.startTime == t.getStartTime() && this.finishedTime == t.getFinishTime() &&
this.executionDuration == t.getExecutionTime() && this.description.equals(t.getDescription());
}
}
| true | true | public static Task parseJson(JSONObject jsonTask) {
String name = jsonTask.get("name").isString().stringValue();
JSONObject taskInfo = jsonTask.get("taskInfo").isObject();
String hostName = "";
if (taskInfo.containsKey("executionHostName")) {
JSONString host = taskInfo.get("executionHostName").isString();
if (host != null) {
hostName = host.stringValue();
}
}
long id = (long) taskInfo.get("taskId").isObject().get("id").isNumber().doubleValue();
String status = taskInfo.get("taskStatus").isString().stringValue();
long startTime = (long) taskInfo.get("startTime").isNumber().doubleValue();
long finishedTime = (long) taskInfo.get("finishedTime").isNumber().doubleValue();
long executionDuration = (long) taskInfo.get("executionDuration").isNumber().doubleValue();
String description = "";
if (jsonTask.containsKey("description")) {
JSONString desc = jsonTask.get("description").isString();
if (desc != null)
description = desc.stringValue();
}
int maxExec = (int) jsonTask.get("maxNumberOfExecution").isObject().get("value").isObject().get(
"value").isNumber().doubleValue();
int execLeft = (int) taskInfo.get("numberOfExecutionLeft").isNumber().doubleValue();
int execOnFailureLeft = (int) taskInfo.get("numberOfExecutionOnFailureLeft").isNumber().doubleValue();
int maxExecOnFailure = (int) jsonTask.get("maxNumberOfExecutionOnFailure").isNumber().doubleValue();
int nodes = 1;
if (jsonTask.containsKey("parallelEnvironment")) {
JSONObject parEnv = jsonTask.get("parallelEnvironment").isObject();
if (parEnv != null && parEnv.containsKey("nodesNumber")) {
nodes = (int) parEnv.get("nodesNumber").isNumber().doubleValue();
}
}
return new Task(id, name, TaskStatus.valueOf(status), hostName, startTime, finishedTime,
executionDuration, description, nodes, execLeft, maxExec, maxExecOnFailure, execOnFailureLeft);
}
| public static Task parseJson(JSONObject jsonTask) {
String name = jsonTask.get("name").isString().stringValue();
JSONObject taskInfo = jsonTask.get("taskInfo").isObject();
String hostName = "";
if (taskInfo.containsKey("executionHostName")) {
JSONString host = taskInfo.get("executionHostName").isString();
if (host != null) {
hostName = host.stringValue();
}
}
long id = (long) taskInfo.get("taskId").isObject().get("id").isNumber().doubleValue();
String status = taskInfo.get("taskStatus").isString().stringValue();
long startTime = (long) taskInfo.get("startTime").isNumber().doubleValue();
long finishedTime = (long) taskInfo.get("finishedTime").isNumber().doubleValue();
long executionDuration = (long) taskInfo.get("executionDuration").isNumber().doubleValue();
String description = "";
if (jsonTask.containsKey("description")) {
JSONString desc = jsonTask.get("description").isString();
if (desc != null)
description = desc.stringValue();
}
int maxExec = (int) jsonTask.get("maxNumberOfExecution").isNumber().doubleValue();
int execLeft = (int) taskInfo.get("numberOfExecutionLeft").isNumber().doubleValue();
int execOnFailureLeft = (int) taskInfo.get("numberOfExecutionOnFailureLeft").isNumber().doubleValue();
int maxExecOnFailure = (int) jsonTask.get("maxNumberOfExecutionOnFailure").isNumber().doubleValue();
int nodes = 1;
if (jsonTask.containsKey("parallelEnvironment")) {
JSONObject parEnv = jsonTask.get("parallelEnvironment").isObject();
if (parEnv != null && parEnv.containsKey("nodesNumber")) {
nodes = (int) parEnv.get("nodesNumber").isNumber().doubleValue();
}
}
return new Task(id, name, TaskStatus.valueOf(status), hostName, startTime, finishedTime,
executionDuration, description, nodes, execLeft, maxExec, maxExecOnFailure, execOnFailureLeft);
}
|
diff --git a/src/ljdp/minechem/common/PotionInjector.java b/src/ljdp/minechem/common/PotionInjector.java
index a6e248a..6e8bb63 100644
--- a/src/ljdp/minechem/common/PotionInjector.java
+++ b/src/ljdp/minechem/common/PotionInjector.java
@@ -1,37 +1,37 @@
package ljdp.minechem.common;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import net.minecraft.potion.Potion;
public class PotionInjector {
public static Potion atropineHigh;
public static void inject() {
int potionTotal = Potion.potionTypes.length;
- Potion[] effectAray = new Potion[potionTotal + 2];
+ Potion[] effectAray = new Potion[potionTotal + 1];
System.arraycopy(Potion.potionTypes, 0, effectAray, 0, potionTotal);
Field field = null;
Field[] fields = Potion.class.getDeclaredFields();
for (Field f : fields)
if (f.getName().equals("potionTypes")
|| f.getName().equals("field_76425_a")) {
field = f;
break;
}
try {
field.setAccessible(true);
Field modfield = Field.class.getDeclaredField("modifiers");
modfield.setAccessible(true);
modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, effectAray);
} catch (Exception e) {
System.err.println("He's Dead Jim" + " " + e);
}
- atropineHigh = new PotionProvider(potionTotal, true, 0x00FF6E).setPotionName("Delirium").setIconIndex(2, 1); // That icon is a refrence to alice in wonderland :P
+ atropineHigh = new PotionProvider(potionTotal, true, 0x00FF6E).setPotionName("Delirium").setIconIndex(2, 1);
}
}
| false | true | public static void inject() {
int potionTotal = Potion.potionTypes.length;
Potion[] effectAray = new Potion[potionTotal + 2];
System.arraycopy(Potion.potionTypes, 0, effectAray, 0, potionTotal);
Field field = null;
Field[] fields = Potion.class.getDeclaredFields();
for (Field f : fields)
if (f.getName().equals("potionTypes")
|| f.getName().equals("field_76425_a")) {
field = f;
break;
}
try {
field.setAccessible(true);
Field modfield = Field.class.getDeclaredField("modifiers");
modfield.setAccessible(true);
modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, effectAray);
} catch (Exception e) {
System.err.println("He's Dead Jim" + " " + e);
}
atropineHigh = new PotionProvider(potionTotal, true, 0x00FF6E).setPotionName("Delirium").setIconIndex(2, 1); // That icon is a refrence to alice in wonderland :P
}
| public static void inject() {
int potionTotal = Potion.potionTypes.length;
Potion[] effectAray = new Potion[potionTotal + 1];
System.arraycopy(Potion.potionTypes, 0, effectAray, 0, potionTotal);
Field field = null;
Field[] fields = Potion.class.getDeclaredFields();
for (Field f : fields)
if (f.getName().equals("potionTypes")
|| f.getName().equals("field_76425_a")) {
field = f;
break;
}
try {
field.setAccessible(true);
Field modfield = Field.class.getDeclaredField("modifiers");
modfield.setAccessible(true);
modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, effectAray);
} catch (Exception e) {
System.err.println("He's Dead Jim" + " " + e);
}
atropineHigh = new PotionProvider(potionTotal, true, 0x00FF6E).setPotionName("Delirium").setIconIndex(2, 1);
}
|
diff --git a/src/didproject/DBManager.java b/src/didproject/DBManager.java
index 366dd84..fb40827 100755
--- a/src/didproject/DBManager.java
+++ b/src/didproject/DBManager.java
@@ -1,277 +1,280 @@
package didproject;
import java.sql.*;
import java.util.*;
//import DBaccess;
//******************************************************************************
class DBManager {
private String host, port, user, password, dbname;
int n;
public ArrayList<String> getIds(String tblName, String tblID) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT `" + tblID + "` FROM `" + tblName
+ "`");
while (rs.next()) {
result.add(rs.getString(tblID));
}
} catch (Exception e) {
} finally {
DBaccess.disconnect();
return result;
}
}
public int exists(String returnField, String tblName, String field,
String value) {
int id = -1;
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT `" + returnField + "` FROM `"
+ tblName + "` WHERE " + field + "='" + value + "'");
if (!rs.first()) {
// System.err.println("<exists> ERROR: No results.");
id = -1;
} else {
id = Integer.parseInt(rs.getString(returnField));
}
} catch (Exception e) {
System.err.println("Error parsing ID from <exists>");
} finally {
DBaccess.disconnect();
return id;
}
}
public String returnStringField(String returnField, String tblName,
String field, String value) {
String id = "";
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT `" + returnField + "` FROM `"
+ tblName + "` WHERE " + field + "='" + value + "'");
if (!rs.first()) {
// System.err.println("<exists> ERROR: No results.");
id = "";
} else {
id = rs.getString(returnField);
}
} catch (Exception e) {
System.err.println("Error parsing ID from <exists>");
} finally {
DBaccess.disconnect();
return id;
}
}
public void updateEpisode(int castawayID, String field, String value) {
String q = "UPDATE episode SET " + field + " = " + value
+ " WHERE castawayID = '" + castawayID + "'";
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update(q);
System.err.println("update Age per episode: " + q);
DBaccess.disconnect();
}
public void addClassifiedIn(int castawayID, int categoryID) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO classifiedIn (castawayID,categoryID) VALUES ("
+ castawayID + "," + categoryID + ")");
DBaccess.disconnect();
}
public void addGenreOf(int genreID, int recordID) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO recordOf (genreID,recordID) VALUES ("
+ genreID + "," + recordID + ")");
DBaccess.disconnect();
}
public void addWorksAs(int castawayID, int occupationID) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO worksAs (castawayID,occupationID) VALUES ("
+ castawayID + "," + occupationID + ")");
DBaccess.disconnect();
}
public void addCategory(String name) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO category (name) VALUES ('" + name + "')");
DBaccess.disconnect();
}
public void addGenre(String name) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO genre (name) VALUES ('" + name + "')");
DBaccess.disconnect();
}
public void addOccupation(String name) {
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update("INSERT INTO occupation (name) VALUES ('" + name + "')");
DBaccess.disconnect();
}
public void flagCastaway(int id, String field, int value) {
String q = "UPDATE castaway SET " + field + " = " + value
+ " WHERE castawayID = '" + id + "'";
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update(q);
System.err.println("UPDATE: " + q);
DBaccess.disconnect();
}
public void updateRecord(int id, String releasedOn, String artistURI,
String songURI, String artistComment, String gender,
double genderRatio, String categories_record,
String categories_artist, int bound) {
String q = "UPDATE record SET releasedOn = " + releasedOn
+ ", artistURI=" + artistURI + ", songURI=" + songURI
+ ", artistComment=" + artistComment + ", gender=" + gender
+ ",genderRatio=" + genderRatio + ", categories_record="
+ categories_record + ", categories_artist="
+ categories_artist + ", bound = "+bound+" WHERE recordID = '" + id + "'";
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update(q);
System.err.println("UPDATE record "+id+":" + q);
DBaccess.disconnect();
}
public void addDoBCastaway(int id, String field, int value) {
String q = "UPDATE castaway SET " + field + " = " + value
+ " WHERE castawayID = '" + id + "'";
DBaccess.connect(host, port, user, password, dbname);
DBaccess.update(q);
DBaccess.disconnect();
}
public ArrayList<String> getCastaway(String tblName, String id) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT * FROM `" + tblName + "` WHERE `"
+ tblName + "ID` = '" + id + "'");
if (!rs.first()) {
System.err.println("TS_ERROR: Castaway does not exist.");
return null;
}
result.add(rs.getString("castawayID"));
result.add(rs.getString("name"));
result.add(rs.getString("link"));
result.add(rs.getString("gender"));
result.add(rs.getString("occupation"));
} catch (Exception e) {
System.err.println("ERROR: Get Castaway e.getm: " + e.getMessage());
} finally {
DBaccess.disconnect();
return result;
}
}
public ArrayList<String> getEpisode(String tblName, String id) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT * FROM `" + tblName + "` WHERE `"
+ tblName + "ID` = '" + id + "'");
if (!rs.first()) {
System.err.println("TS_ERROR: Episode does not exist.");
return null;
}
result.add(rs.getString("episodeID"));
result.add(rs.getString("castawayID"));
result.add(rs.getString("luxuryID"));
result.add(rs.getString("dateOfBroadcast"));
result.add(rs.getString("age"));
result.add(rs.getString("occupations"));
} catch (Exception e) {
System.err.println("ERROR: Get Episode e.getm: " + e.getMessage());
} finally {
DBaccess.disconnect();
return result;
}
}
public ArrayList<String> getRecord(String tblName, String id) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT * FROM `" + tblName + "` WHERE `"
+ tblName + "ID` = '" + id + "'");
if (!rs.first()) {
System.err.println("TS_ERROR: Episode does not exist.");
return null;
}
result.add(rs.getString("recordID"));
result.add(rs.getString("artist"));
result.add(rs.getString("title"));
result.add(rs.getString("part_of"));
result.add(rs.getString("composer"));
result.add(rs.getString("releasedOn"));
result.add(rs.getString("artistURI"));
result.add(rs.getString("songURI"));
result.add(rs.getString("artistComment"));
result.add(rs.getString("genderRatio"));
+ result.add(rs.getString("gender"));
+ result.add(rs.getString("categories_record"));
+ result.add(rs.getString("categories_artist"));
result.add(rs.getString("bound"));
} catch (Exception e) {
System.err.println("ERROR: Get Record e.getm: " + e.getMessage());
} finally {
DBaccess.disconnect();
return result;
}
}
// //
// // public int size(String tblName) {
// try {
// DBaccess.connect(host, port, user, password, dbname);
// ResultSet rs = DBaccess.retrieve("SELECT COUNT(*) FROM `" + tblName
// + "`");
// rs.first();
// n = Integer.parseInt(rs.getString("COUNT(*)"));
// System.err.println("TS____ N= " + n);
// } catch (SQLException ex) {
// System.err.println("TS_SQL_ERR_INS = " + ex.getMessage());
// System.err.println("SELECT COUNT(*) FROM \"" + tblName + "\"");
// } catch (NumberFormatException ex) {
// System.err.println("TS_SQL_NUMFORMAT_INS = " + ex.getMessage());
// } finally {
// DBaccess.disconnect();
// return n;
// }
//
// }
}
| true | true | public ArrayList<String> getRecord(String tblName, String id) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT * FROM `" + tblName + "` WHERE `"
+ tblName + "ID` = '" + id + "'");
if (!rs.first()) {
System.err.println("TS_ERROR: Episode does not exist.");
return null;
}
result.add(rs.getString("recordID"));
result.add(rs.getString("artist"));
result.add(rs.getString("title"));
result.add(rs.getString("part_of"));
result.add(rs.getString("composer"));
result.add(rs.getString("releasedOn"));
result.add(rs.getString("artistURI"));
result.add(rs.getString("songURI"));
result.add(rs.getString("artistComment"));
result.add(rs.getString("genderRatio"));
result.add(rs.getString("bound"));
} catch (Exception e) {
System.err.println("ERROR: Get Record e.getm: " + e.getMessage());
} finally {
DBaccess.disconnect();
return result;
}
}
| public ArrayList<String> getRecord(String tblName, String id) {
ArrayList<String> result = new ArrayList<String>();
ResultSet rs;
try {
DBaccess.connect(host, port, user, password, dbname);
rs = DBaccess.retrieve("SELECT * FROM `" + tblName + "` WHERE `"
+ tblName + "ID` = '" + id + "'");
if (!rs.first()) {
System.err.println("TS_ERROR: Episode does not exist.");
return null;
}
result.add(rs.getString("recordID"));
result.add(rs.getString("artist"));
result.add(rs.getString("title"));
result.add(rs.getString("part_of"));
result.add(rs.getString("composer"));
result.add(rs.getString("releasedOn"));
result.add(rs.getString("artistURI"));
result.add(rs.getString("songURI"));
result.add(rs.getString("artistComment"));
result.add(rs.getString("genderRatio"));
result.add(rs.getString("gender"));
result.add(rs.getString("categories_record"));
result.add(rs.getString("categories_artist"));
result.add(rs.getString("bound"));
} catch (Exception e) {
System.err.println("ERROR: Get Record e.getm: " + e.getMessage());
} finally {
DBaccess.disconnect();
return result;
}
}
|
diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/NativeEntryEntityPersister.java b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/NativeEntryEntityPersister.java
index c0e30977..4ad876e8 100644
--- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/NativeEntryEntityPersister.java
+++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/NativeEntryEntityPersister.java
@@ -1,1658 +1,1660 @@
/* Copyright (C) 2010 SpringSource
*
* 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.grails.datastore.mapping.engine;
import java.io.Serializable;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.FlushModeType;
import org.grails.datastore.mapping.cache.TPCacheAdapter;
import org.grails.datastore.mapping.cache.TPCacheAdapterRepository;
import org.grails.datastore.mapping.collection.*;
import org.grails.datastore.mapping.engine.internal.MappingUtils;
import org.grails.datastore.mapping.engine.types.CustomTypeMarshaller;
import org.grails.datastore.mapping.model.*;
import org.grails.datastore.mapping.model.types.*;
import org.grails.datastore.mapping.query.Query;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.CannotAcquireLockException;
import org.grails.datastore.mapping.config.Property;
import org.grails.datastore.mapping.core.Session;
import org.grails.datastore.mapping.core.SessionImplementor;
import org.grails.datastore.mapping.core.impl.PendingInsert;
import org.grails.datastore.mapping.core.impl.PendingInsertAdapter;
import org.grails.datastore.mapping.core.impl.PendingOperation;
import org.grails.datastore.mapping.core.impl.PendingOperationAdapter;
import org.grails.datastore.mapping.core.impl.PendingOperationExecution;
import org.grails.datastore.mapping.core.impl.PendingUpdate;
import org.grails.datastore.mapping.core.impl.PendingUpdateAdapter;
import org.grails.datastore.mapping.engine.event.PreDeleteEvent;
import org.grails.datastore.mapping.proxy.ProxyFactory;
/**
* Provides an implementation of the {@link org.grails.datastore.mapping.engine.EntityPersister} class that
* reads and writes against a native datastore type specified by the generic type parameter T
*
* @author Graeme Rocher
* @since 1.0
*/
@SuppressWarnings({"unused", "rawtypes", "unchecked"})
public abstract class NativeEntryEntityPersister<T, K> extends LockableEntityPersister {
protected ClassMapping classMapping;
protected TPCacheAdapterRepository<T> cacheAdapterRepository;
public NativeEntryEntityPersister(MappingContext mappingContext, PersistentEntity entity,
Session session, ApplicationEventPublisher publisher) {
super(mappingContext, entity, session, publisher);
classMapping = entity.getMapping();
}
public NativeEntryEntityPersister(MappingContext mappingContext, PersistentEntity entity,
Session session, ApplicationEventPublisher publisher, TPCacheAdapterRepository<T> cacheAdapterRepository) {
super(mappingContext, entity, session, publisher);
classMapping = entity.getMapping();
this.cacheAdapterRepository = cacheAdapterRepository;
}
public abstract String getEntityFamily();
public ClassMapping getClassMapping() {
return classMapping;
}
/**
* Subclasses should override to optimize away manual property indexing if it is not required
*
* @return True if property indexing is required (the default)
*/
protected boolean doesRequirePropertyIndexing() { return true; }
@Override
protected void deleteEntity(PersistentEntity persistentEntity, Object obj) {
if (obj == null) {
return;
}
EntityAccess entityAccess = createEntityAccess(persistentEntity, obj);
PreDeleteEvent event = new PreDeleteEvent(session.getDatastore(), persistentEntity, entityAccess);
publisher.publishEvent(event);
if (event.isCancelled()) {
return;
}
final K key = readIdentifierFromObject(obj);
if (key == null) {
return;
}
FlushModeType flushMode = session.getFlushMode();
try {
session.setFlushMode(FlushModeType.COMMIT);
cascadeBeforeDelete(persistentEntity, entityAccess, key, obj);
deleteEntry(getEntityFamily(), key, obj);
cascadeAfterDelete(persistentEntity, entityAccess, key, obj);
}
finally {
session.setFlushMode(flushMode);
}
firePostDeleteEvent(persistentEntity, entityAccess);
}
protected void cascadeDeleteCollection(Collection collection) {
for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
Object child = iter.next();
deleteEntity(getMappingContext().getPersistentEntity(child.getClass().getName()), child);
iter.remove();
}
}
@Override
protected EntityAccess createEntityAccess(PersistentEntity persistentEntity, Object obj) {
EntityAccess entityAccess = new EntityAccess(persistentEntity, obj);
entityAccess.setConversionService(getMappingContext().getConversionService());
return entityAccess;
}
protected EntityAccess createEntityAccess(PersistentEntity persistentEntity, Object obj, final T nativeEntry) {
final NativeEntryModifyingEntityAccess ea = new NativeEntryModifyingEntityAccess(persistentEntity, obj);
ea.setConversionService(getMappingContext().getConversionService());
ea.setNativeEntry(nativeEntry);
return ea;
}
/**
* Deletes a single entry
*
* @param family The family
* @param key The key
* @param entry the entry
*/
protected abstract void deleteEntry(String family, K key, Object entry);
/**
* Delete collections before owner delete.
*/
protected void cascadeBeforeDelete(PersistentEntity persistentEntity, EntityAccess entityAccess,
K key, Object instance) {
List<PersistentProperty> props = persistentEntity.getPersistentProperties();
for (PersistentProperty prop : props) {
String propertyKey = getPropertyKey(prop);
if (prop instanceof OneToMany) {
OneToMany oneToMany = (OneToMany)prop;
if (oneToMany.isOwningSide() && oneToMany.doesCascade(CascadeType.REMOVE)) {
Object propValue = entityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
cascadeDeleteCollection((Collection) propValue);
}
}
}
else if (prop instanceof ManyToMany) {
ManyToMany manyToMany = (ManyToMany)prop;
if (manyToMany.isOwningSide() && manyToMany.doesCascade(CascadeType.REMOVE)) {
Object propValue = entityAccess.getProperty(manyToMany.getName());
if (propValue instanceof Collection) {
cascadeDeleteCollection((Collection) propValue);
}
}
}
}
}
/**
* Delete many-to-ones after owner delete.
*/
protected void cascadeAfterDelete(PersistentEntity persistentEntity, EntityAccess entityAccess,
K key, Object instance) {
List<PersistentProperty> props = persistentEntity.getPersistentProperties();
for (PersistentProperty prop : props) {
String propertyKey = getPropertyKey(prop);
if (prop instanceof Basic) {
Object propValue = entityAccess.getProperty(prop.getName());
}
else if (prop instanceof OneToMany) {
OneToMany oneToMany = (OneToMany)prop;
if (oneToMany.isOwningSide() && oneToMany.doesCascade(CascadeType.REMOVE)) {
Object propValue = entityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
cascadeDeleteCollection((Collection) propValue);
}
}
}
else if (prop instanceof ToOne) {
ToOne association = (ToOne) prop;
if (!(prop instanceof Embedded) && !(prop instanceof EmbeddedCollection) &&
association.doesCascade(CascadeType.REMOVE)) {
if(association.isOwningSide()) {
Object value = entityAccess.getProperty(association.getName());
if(value != null) {
Persister persister = session.getPersister(value);
if(persister != null)
persister.delete(value);
}
}
}
}
}
}
@Override
protected final void deleteEntities(PersistentEntity persistentEntity, Iterable objects) {
if (objects != null) {
final List<K> keys = new ArrayList<K>();
for (Object object : objects) {
K key = readIdentifierFromObject(object);
if (key != null) {
keys.add(key);
}
}
if (!keys.isEmpty()) {
deleteEntries(getEntityFamily(), keys);
}
}
}
protected K readIdentifierFromObject(Object object) {
EntityAccess access = createEntityAccess(getPersistentEntity(), object);
final Object idValue = access.getIdentifier();
Object key = null;
if (idValue != null) {
key = inferNativeKey(getEntityFamily(), idValue);
}
return (K) key;
}
@Override
public final Object lock(Serializable id) throws CannotAcquireLockException {
return lock(id, DEFAULT_TIMEOUT);
}
@Override
public final Object lock(Serializable id, int timeout) throws CannotAcquireLockException {
lockEntry(getPersistentEntity(), getEntityFamily(), id, timeout);
return retrieve(id);
}
/**
* Subclasses can override to provide locking semantics
*
* @param persistentEntity The PesistentEntity instnace
* @param entityFamily The family
* @param id The identifer
* @param timeout The lock timeout in seconds
*/
protected void lockEntry(PersistentEntity persistentEntity, String entityFamily, Serializable id, int timeout) {
// do nothing,
}
/**
* Subclasses can override to provide locking semantics
*
* @param o The object
* @return True if the object is locked
*/
@Override
public boolean isLocked(Object o) {
return false;
}
@Override
public void unlock(Object o) {
unlockEntry(getPersistentEntity(), getEntityFamily(), (Serializable) createEntityAccess(getPersistentEntity(), o).getIdentifier());
}
/**
* Subclasses to override to provide locking semantics
* @param persistentEntity The persistent entity
* @param entityFamily The entity family
* @param id The identifer
*/
protected void unlockEntry(PersistentEntity persistentEntity, String entityFamily, Serializable id) {
// do nothing
}
@Override
protected final Object retrieveEntity(PersistentEntity persistentEntity, Serializable nativeKey) {
final Serializable key = convertToNativeKey(nativeKey);
T nativeEntry = getFromTPCache(persistentEntity, nativeKey);
if (nativeEntry == null) {
nativeEntry = retrieveEntry(persistentEntity, getEntityFamily(), key);
if (nativeEntry == null) {
return null;
}
}
return createObjectFromNativeEntry(persistentEntity, key, nativeEntry);
}
/**
* Subclasses should override to provide any conversion necessary to convert to a nativeKey
*
* @param nativeKey The key
* @return The native key
*/
protected Serializable convertToNativeKey(Serializable nativeKey) {
return nativeKey;
}
public Serializable refresh(Object o) {
final PersistentEntity entity = getPersistentEntity();
EntityAccess ea = createEntityAccess(entity, o);
Serializable identifier = (Serializable) ea.getIdentifier();
if (identifier == null) {
return null;
}
final T entry = retrieveEntry(entity, getEntityFamily(), identifier);
refreshObjectStateFromNativeEntry(entity, o, identifier, entry, false);
return identifier;
}
public Object createObjectFromNativeEntry(PersistentEntity persistentEntity, Serializable nativeKey, T nativeEntry) {
persistentEntity = discriminatePersistentEntity(persistentEntity, nativeEntry);
cacheNativeEntry(persistentEntity, nativeKey, nativeEntry);
Object obj = newEntityInstance(persistentEntity);
refreshObjectStateFromNativeEntry(persistentEntity, obj, nativeKey, nativeEntry, false);
return obj;
}
protected void cacheNativeEntry(PersistentEntity persistentEntity,
Serializable nativeKey, T nativeEntry) {
SessionImplementor<Object> si = (SessionImplementor<Object>) session;
Serializable key = (Serializable) getMappingContext().getConversionService().convert(
nativeKey, persistentEntity.getIdentity().getType());
si.cacheEntry(persistentEntity, key, nativeEntry);
}
protected void refreshObjectStateFromNativeEntry(PersistentEntity persistentEntity, Object obj,
Serializable nativeKey, T nativeEntry) {
refreshObjectStateFromNativeEntry(persistentEntity, obj, nativeKey, nativeEntry, false);
}
protected void refreshObjectStateFromNativeEntry(PersistentEntity persistentEntity, Object obj,
Serializable nativeKey, T nativeEntry, boolean isEmbedded) {
EntityAccess ea = createEntityAccess(persistentEntity, obj, nativeEntry);
ea.setConversionService(getMappingContext().getConversionService());
if(!(persistentEntity instanceof EmbeddedPersistentEntity)) {
String idName = ea.getIdentifierName();
ea.setProperty(idName, nativeKey);
}
final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
for (final PersistentProperty prop : props) {
String propKey = getNativePropertyKey(prop);
if (prop instanceof Simple) {
ea.setProperty(prop.getName(), getEntryValue(nativeEntry, propKey));
}
else if(prop instanceof Basic) {
Object entryValue = getEntryValue(nativeEntry, propKey);
if(entryValue instanceof Map) {
entryValue = new LinkedHashMap((Map) entryValue);
}
else if(entryValue instanceof Collection) {
Collection collection = MappingUtils.createConcreteCollection(prop.getType());
Class propertyType = prop.getType();
Class genericType = MappingUtils.getGenericTypeForProperty(persistentEntity.getJavaClass(), prop.getName());
Collection collectionValue = (Collection) entryValue;
if(genericType != null && genericType.isEnum()) {
for (Object o : collectionValue) {
if(!(o instanceof Enum)) {
collection.add( Enum.valueOf(genericType, o.toString()) );
}
}
}
else {
collection.addAll(collectionValue);
}
entryValue = collection;
}
ea.setProperty(prop.getName(), entryValue);
}
else if (prop instanceof Custom) {
handleCustom(prop, ea, nativeEntry);
}
else if (prop instanceof ToOne) {
if (prop instanceof Embedded) {
Embedded embedded = (Embedded) prop;
T embeddedEntry = getEmbedded(nativeEntry, propKey);
if (embeddedEntry != null) {
Object embeddedInstance = newEntityInstance(embedded.getAssociatedEntity());
createEntityAccess(embedded.getAssociatedEntity(), embeddedInstance);
refreshObjectStateFromNativeEntry(embedded.getAssociatedEntity(),
embeddedInstance, null, embeddedEntry, true);
ea.setProperty(propKey, embeddedInstance);
}
}
else {
ToOne association = (ToOne) prop;
Serializable tmp = null;
if (!association.isForeignKeyInChild()) {
tmp = (Serializable) getEntryValue(nativeEntry, propKey);
}
else {
if (association.isBidirectional()) {
Query query = session.createQuery(association.getAssociatedEntity().getJavaClass());
query.eq(association.getInverseSide().getName(), obj)
.projections().id();
tmp = (Serializable) query.singleResult();
}
else {
// TODO: handle unidirectional?
}
}
if (isEmbeddedEntry(tmp)) {
PersistentEntity associatedEntity = ((ToOne) prop).getAssociatedEntity();
Object instance = newEntityInstance(associatedEntity);
refreshObjectStateFromNativeEntry(associatedEntity,instance, null, (T) tmp, false);
ea.setProperty(prop.getName(), instance);
}
else if (tmp != null && !prop.getType().isInstance(tmp)) {
PersistentEntity associatedEntity = association.getAssociatedEntity();
final Serializable associationKey = (Serializable) getMappingContext().getConversionService().convert(
tmp, associatedEntity.getIdentity().getType());
if (associationKey != null) {
PropertyMapping<Property> associationPropertyMapping = prop.getMapping();
boolean isLazy = isLazyAssociation(associationPropertyMapping);
final Class propType = prop.getType();
if (isLazy) {
Object proxy = getProxyFactory().createProxy(session, propType, associationKey);
ea.setProperty(prop.getName(), proxy);
}
else {
ea.setProperty(prop.getName(), session.retrieve(propType, associationKey));
}
}
}
}
}
else if (prop instanceof EmbeddedCollection) {
final Object embeddedInstances = getEntryValue(nativeEntry, propKey);
loadEmbeddedCollection((EmbeddedCollection)prop, ea, embeddedInstances, propKey);
}
else if (prop instanceof OneToMany) {
Association association = (Association) prop;
PropertyMapping<Property> associationPropertyMapping = association.getMapping();
if(isEmbedded) {
List keys = loadEmbeddedCollectionKeys((Association) prop, ea, nativeEntry);
if (List.class.isAssignableFrom(association.getType())) {
ea.setPropertyNoConversion(association.getName(),
new PersistentList(keys, association.getAssociatedEntity().getJavaClass(), session));
}
else if (Set.class.isAssignableFrom(association.getType())) {
ea.setPropertyNoConversion(association.getName(),
new PersistentSet(keys, association.getAssociatedEntity().getJavaClass(), session));
}
}
else {
boolean isLazy = isLazyAssociation(associationPropertyMapping);
AssociationIndexer indexer = getAssociationIndexer(nativeEntry, association);
nativeKey = (Serializable) getMappingContext().getConversionService().convert(
nativeKey, getPersistentEntity().getIdentity().getType());
if (isLazy) {
if (List.class.isAssignableFrom(association.getType())) {
ea.setPropertyNoConversion(association.getName(),
new PersistentList(nativeKey, session, indexer));
}
else if (SortedSet.class.isAssignableFrom(association.getType())) {
ea.setPropertyNoConversion(association.getName(),
new PersistentSortedSet(nativeKey, session, indexer));
}
else if (Set.class.isAssignableFrom(association.getType())) {
ea.setPropertyNoConversion(association.getName(),
new PersistentSet(nativeKey, session, indexer));
}
}
else {
if (indexer != null) {
List keys = indexer.query(nativeKey);
ea.setProperty(association.getName(),
session.retrieveAll(association.getAssociatedEntity().getJavaClass(), keys));
}
}
}
}
else if (prop instanceof ManyToMany) {
ManyToMany manyToMany = (ManyToMany) prop;
PropertyMapping<Property> associationPropertyMapping = manyToMany.getMapping();
boolean isLazy = isLazyAssociation(associationPropertyMapping);
nativeKey = (Serializable) getMappingContext().getConversionService().convert(
nativeKey, getPersistentEntity().getIdentity().getType());
Class childType = manyToMany.getAssociatedEntity().getJavaClass();
Collection cached = ((SessionImplementor)session).getCachedCollection(
persistentEntity, nativeKey, manyToMany.getName());
if (cached == null) {
Collection collection;
if (isLazy) {
Collection keys = getManyToManyKeys(persistentEntity, obj, nativeKey,
nativeEntry, manyToMany);
if (List.class.isAssignableFrom(manyToMany.getType())) {
collection = new PersistentList(keys, childType, session);
ea.setPropertyNoConversion(manyToMany.getName(), collection);
}
else if (Set.class.isAssignableFrom(manyToMany.getType())) {
collection = new PersistentSet(keys, childType, session);
ea.setPropertyNoConversion(manyToMany.getName(), collection);
}
else {
collection = Collections.emptyList();
}
}
else {
AssociationIndexer indexer = getAssociationIndexer(nativeEntry, manyToMany);
if (indexer == null) {
if (List.class.isAssignableFrom(manyToMany.getType())) {
collection = Collections.emptyList();
}
else if (Set.class.isAssignableFrom(manyToMany.getType())) {
collection = Collections.emptySet();
}
else {
collection = Collections.emptyList();
}
}
else {
List keys = indexer.query(nativeKey);
collection = session.retrieveAll(childType, keys);
ea.setProperty(manyToMany.getName(), collection);
}
}
((SessionImplementor)session).cacheCollection(
persistentEntity, nativeKey, collection, manyToMany.getName());
}
else {
ea.setProperty(manyToMany.getName(), cached);
}
}
}
}
/**
* Implementors who want to support one-to-many associations embedded should implement this method
*
* @param association The association
* @param ea
* @param nativeEntry
*
* @return A list of keys loaded from the embedded instance
*/
protected List loadEmbeddedCollectionKeys(Association association, EntityAccess ea, T nativeEntry) {
// no out of the box support
return Collections.emptyList();
}
protected void setEmbeddedCollectionKeys(Association association, EntityAccess embeddedEntityAccess, T embeddedEntry, List<Serializable> keys) {
// do nothing
}
/**
* Tests whether a native entry is an embedded entry
*
* @param entry The native entry
* @return True if it is embedded
*/
protected boolean isEmbeddedEntry(Object entry) {
return false;
}
/**
* Implementors who want to the ability to read embedded collections should implement this method
*
* @param embeddedCollection The EmbeddedCollection instance
* @param ea The EntityAccess instance
* @param embeddedInstances The embedded instances
* @param propertyKey The property key
*/
protected void loadEmbeddedCollection(EmbeddedCollection embeddedCollection, EntityAccess ea,
Object embeddedInstances, String propertyKey) {
// no support by default for embedded collections
}
/**
* Implementors should override to provide support for embedded objects.
*
* @param nativeEntry The native entry to read the embedded instance from
* @param key The key
* @return The native entry of the embedded instance
*/
protected T getEmbedded(T nativeEntry, String key) {
return null;
}
private void handleCustom(PersistentProperty prop, EntityAccess ea, T nativeEntry) {
CustomTypeMarshaller customTypeMarshaller = ((Custom) prop).getCustomTypeMarshaller();
if (!customTypeMarshaller.supports(getSession().getDatastore())) {
return;
}
Object value = customTypeMarshaller.read(prop, nativeEntry);
ea.setProperty(prop.getName(), value);
}
protected Collection getManyToManyKeys(PersistentEntity persistentEntity, Object obj,
Serializable nativeKey, T nativeEntry, ManyToMany manyToMany) {
return null;
}
protected String getNativePropertyKey(PersistentProperty prop) {
PropertyMapping<Property> pm = prop.getMapping();
String propKey = null;
if (pm.getMappedForm()!=null) {
propKey = pm.getMappedForm().getTargetName();
}
if (propKey == null) {
propKey = prop.getName();
}
return propKey;
}
/**
* Subclasses should override to customize how entities in hierarchies are discriminated
* @param persistentEntity The PersistentEntity
* @param nativeEntry The native entry
* @return The discriminated entity
*/
protected PersistentEntity discriminatePersistentEntity(PersistentEntity persistentEntity, T nativeEntry) {
return persistentEntity;
}
private boolean isLazyAssociation(PropertyMapping<Property> associationPropertyMapping) {
if (associationPropertyMapping == null) {
return true;
}
Property kv = associationPropertyMapping.getMappedForm();
return kv.getFetchStrategy() == FetchType.LAZY;
}
@Override
protected final Serializable persistEntity(final PersistentEntity persistentEntity, Object obj) {
T tmp = null;
final NativeEntryModifyingEntityAccess entityAccess = (NativeEntryModifyingEntityAccess) createEntityAccess(persistentEntity, obj, tmp);
K k = readObjectIdentifier(entityAccess, persistentEntity.getMapping());
boolean isUpdate = k != null;
boolean assignedId = false;
if (isUpdate && !getSession().isDirty(obj)) {
return (Serializable) k;
}
PendingOperation<T, K> pendingOperation;
PropertyMapping mapping = persistentEntity.getIdentity().getMapping();
if(mapping != null) {
Property p = (Property) mapping.getMappedForm();
assignedId = p != null && "assigned".equals(p.getGenerator());
if(assignedId) {
if(isUpdate && !session.contains(obj)) {
isUpdate = false;
}
}
}
String family = getEntityFamily();
SessionImplementor<Object> si = (SessionImplementor<Object>) session;
if (!isUpdate) {
tmp = createNewEntry(family);
if(!assignedId)
k = generateIdentifier(persistentEntity, tmp);
cacheNativeEntry(persistentEntity, (Serializable) k, tmp);
pendingOperation = new PendingInsertAdapter<T, K>(persistentEntity, k, tmp, entityAccess) {
public void run() {
executeInsert(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
}
};
entityAccess.setProperty(entityAccess.getIdentifierName(), k);
}
else {
tmp = (T) si.getCachedEntry(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = getFromTPCache(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = retrieveEntry(persistentEntity, family, (Serializable) k);
}
}
if (tmp == null) {
tmp = createNewEntry(family);
}
final T finalTmp = tmp;
final K finalK = k;
pendingOperation = new PendingUpdateAdapter<T, K>(persistentEntity, finalK, finalTmp, entityAccess) {
public void run() {
if (cancelUpdate(persistentEntity, entityAccess)) return;
updateEntry(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
updateTPCache(persistentEntity, finalTmp, (Serializable) finalK);
firePostUpdateEvent(persistentEntity, entityAccess);
}
};
}
final T e = tmp;
entityAccess.setNativeEntry(e);
final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
final Map<Association, List<Serializable>> toManyKeys = new HashMap<Association, List<Serializable>>();
final Map<OneToMany, Serializable> inverseCollectionUpdates = new HashMap<OneToMany, Serializable>();
final Map<PersistentProperty, Object> toIndex = new HashMap<PersistentProperty, Object>();
final Map<PersistentProperty, Object> toUnindex = new HashMap<PersistentProperty, Object>();
entityAccess.setToIndex(toIndex);
for (PersistentProperty prop : props) {
PropertyMapping<Property> pm = prop.getMapping();
final Property mappedProperty = pm.getMappedForm();
String key = null;
if (mappedProperty != null) {
key = mappedProperty.getTargetName();
}
if (key == null) key = prop.getName();
final boolean indexed = isPropertyIndexed(mappedProperty);
if ((prop instanceof Simple) || (prop instanceof Basic)) {
Object propValue = entityAccess.getProperty(prop.getName());
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, propValue);
setEntryValue(e, key, propValue);
}
else if ((prop instanceof Custom)) {
CustomTypeMarshaller customTypeMarshaller = ((Custom) prop).getCustomTypeMarshaller();
if (customTypeMarshaller.supports(getSession().getDatastore())) {
Object propValue = entityAccess.getProperty(prop.getName());
Object customValue = customTypeMarshaller.write(prop, propValue, e);
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, customValue);
}
}
else if (prop instanceof OneToMany) {
final OneToMany oneToMany = (OneToMany) prop;
final Object propValue = entityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if (isInitializedCollection(associatedObjects)) {
EntityPersister associationPersister = (EntityPersister) session.getPersister(oneToMany.getAssociatedEntity());
if(associationPersister != null) {
PersistentCollection persistentCollection;
boolean newCollection = false;
if(associatedObjects instanceof PersistentCollection) {
persistentCollection = (PersistentCollection) associatedObjects;
}
else {
Class associationType = oneToMany.getAssociatedEntity().getJavaClass();
persistentCollection = getPersistentCollection(associatedObjects, associationType);
entityAccess.setProperty(oneToMany.getName(), persistentCollection);
persistentCollection.markDirty();
newCollection = true;
}
if(persistentCollection.isDirty()) {
persistentCollection.resetDirty();
List<Serializable> keys = associationPersister.persist(associatedObjects);
toManyKeys.put(oneToMany, keys);
if(newCollection ) {
entityAccess.setProperty(oneToMany.getName(), associatedObjects);
}
}
}
}
}
}
else if (prop instanceof ManyToMany) {
final ManyToMany manyToMany = (ManyToMany) prop;
final Object propValue = entityAccess.getProperty(manyToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if(isInitializedCollection(associatedObjects)) {
setManyToMany(persistentEntity, obj, e, manyToMany, associatedObjects, toManyKeys);
}
}
}
else if (prop instanceof ToOne) {
ToOne association = (ToOne) prop;
if (prop instanceof Embedded) {
// For embedded properties simply set the entry value, the underlying implementation
// will have to store the embedded entity in an appropriate way (as a sub-document in a document store for example)
handleEmbeddedToOne(association, key, entityAccess, e);
}
else if (association.doesCascade(CascadeType.PERSIST)) {
final Object associatedObject = entityAccess.getProperty(prop.getName());
if (associatedObject != null) {
@SuppressWarnings("hiding")
ProxyFactory proxyFactory = getProxyFactory();
// never cascade to proxies
if (proxyFactory.isInitialized(associatedObject)) {
Serializable associationId = null;
NativeEntryEntityPersister associationPersister = (NativeEntryEntityPersister) session.getPersister(associatedObject);
if (!session.contains(associatedObject)) {
Serializable tempId = associationPersister.getObjectIdentifier(associatedObject);
if (tempId == null) {
if (association.isOwningSide()) {
tempId = session.persist(associatedObject);
}
}
associationId = tempId;
}
else {
associationId = associationPersister.getObjectIdentifier(associatedObject);
}
// handling of hasOne inverse key
if (association.isForeignKeyInChild()) {
T cachedAssociationEntry = (T) si.getCachedEntry(association.getAssociatedEntity(), associationId);
if (cachedAssociationEntry != null) {
if (association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if (inverseSide != null) {
setEntryValue(cachedAssociationEntry, inverseSide.getName(), formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
else {
setEntryValue(cachedAssociationEntry, key, formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
}
}
if(association.doesCascade(CascadeType.PERSIST)) {
if(association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if(inverseSide != null) {
EntityAccess inverseAccess = new EntityAccess(inverseSide.getOwner(), associatedObject);
inverseAccess.setProperty(inverseSide.getName(), obj);
}
}
associationPersister.persist(associatedObject);
}
}
// handle of standard many-to-one
else {
if (associationId != null) {
if (indexed && doesRequirePropertyIndexing()) {
toIndex.put(prop, associationId);
if (isUpdate) {
Object oldValue = getEntryValue(e, key);
oldValue = oldValue != null ? convertToNativeKey( (Serializable) oldValue) : oldValue;
if (oldValue != null && !oldValue.equals(associationId)) {
toUnindex.put(prop, oldValue);
}
}
}
setEntryValue(e, key, formulateDatabaseReference(persistentEntity, association, associationId));
if (association.isBidirectional()) {
Association inverse = association.getInverseSide();
if (inverse instanceof OneToMany) {
inverseCollectionUpdates.put((OneToMany) inverse, associationId);
}
Object inverseEntity = entityAccess.getProperty(association.getName());
if (inverseEntity != null) {
EntityAccess inverseAccess = createEntityAccess(association.getAssociatedEntity(), inverseEntity);
+ Object entity = entityAccess.getEntity();
if (inverse instanceof OneToMany) {
Collection existingValues = (Collection) inverseAccess.getProperty(inverse.getName());
if (existingValues == null) {
existingValues = MappingUtils.createConcreteCollection(inverse.getType());
inverseAccess.setProperty(inverse.getName(), existingValues);
}
- existingValues.add(entityAccess.getEntity());
+ if(!existingValues.contains(entity))
+ existingValues.add(entity);
}
else if (inverse instanceof ToOne) {
- inverseAccess.setProperty(inverse.getName(), entityAccess.getEntity());
+ inverseAccess.setProperty(inverse.getName(), entity);
}
}
}
}
}
}
}
else {
setEntryValue(e, getPropertyKey(prop), null);
}
}
}
else if (prop instanceof EmbeddedCollection) {
handleEmbeddedToMany(entityAccess, e, prop, key);
}
}
if (!isUpdate) {
// if the identifier is null at this point that means that datastore could not generated an identifer
// and the identifer is generated only upon insert of the entity
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
toIndex.put(persistentEntity.getIdentity(), updateId);
updatePropertyIndices(updateId, toIndex, toUnindex);
}
for (OneToMany inverseCollection : inverseCollectionUpdates.keySet()) {
final Serializable primaryKey = inverseCollectionUpdates.get(inverseCollection);
final NativeEntryEntityPersister inversePersister = (NativeEntryEntityPersister) session.getPersister(inverseCollection.getOwner());
final AssociationIndexer associationIndexer = inversePersister.getAssociationIndexer(e, inverseCollection);
associationIndexer.index(primaryKey, updateId);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
// If the key is still null at this point we have to execute the pending operation now to get the key
if (k == null) {
PendingOperationExecution.executePendingOperation(pendingOperation);
}
else {
si.addPendingInsert((PendingInsert) pendingOperation);
}
}
else {
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
updatePropertyIndices(updateId, toIndex, toUnindex);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
si.addPendingUpdate((PendingUpdate) pendingOperation);
}
return (Serializable) k;
}
private AbstractPersistentCollection getPersistentCollection(Collection associatedObjects, Class associationType) {
if(associatedObjects instanceof Set) {
return associatedObjects instanceof SortedSet ? new PersistentSortedSet(associationType,getSession(), (SortedSet) associatedObjects) : new PersistentSet(associationType, getSession(), associatedObjects);
}
else {
return new PersistentList(associationType,getSession(), (List) associatedObjects);
}
}
private boolean isInitializedCollection(Collection associatedObjects) {
return !(associatedObjects instanceof PersistentCollection) || ((PersistentCollection) associatedObjects).isInitialized();
}
/**
* Formulates a database reference for the given entity, association and association id
*
* @param persistentEntity The entity being persisted
* @param association The association
* @param associationId The association id
* @return A database reference
*/
protected Object formulateDatabaseReference(PersistentEntity persistentEntity, Association association, Serializable associationId) {
return associationId;
}
protected void handleEmbeddedToMany(EntityAccess entityAccess, T e, PersistentProperty prop, String key) {
// For embedded properties simply set the entry value, the underlying implementation
// will have to store the embedded entity in an appropriate way (as a sub-document in a document store for example)
Object embeddedInstances = entityAccess.getProperty(prop.getName());
if (!(embeddedInstances instanceof Collection) || ((Collection)embeddedInstances).isEmpty()) {
return;
}
Collection instances = (Collection)embeddedInstances;
List<T> embeddedEntries = new ArrayList<T>();
for (Object instance : instances) {
T entry = handleEmbeddedInstance((Association) prop, instance);
embeddedEntries.add(entry);
}
setEmbeddedCollection(e, key, instances, embeddedEntries);
}
protected void handleEmbeddedToOne(Association association, String key, EntityAccess entityAccess, T nativeEntry) {
Object embeddedInstance = entityAccess.getProperty(association.getName());
if (embeddedInstance == null) {
return;
}
T embeddedEntry = handleEmbeddedInstance(association, embeddedInstance);
setEmbedded(nativeEntry, key, embeddedEntry);
}
protected T handleEmbeddedInstance(Association association, Object embeddedInstance) {
NativeEntryEntityPersister<T,K> embeddedPersister = (NativeEntryEntityPersister<T,K>) session.getPersister(embeddedInstance);
// embeddedPersister would be null if the associated entity is a EmbeddedPersistentEntity
T embeddedEntry;
if(embeddedPersister == null) {
embeddedEntry = createNewEntry(association.getName());
}
else {
embeddedEntry = embeddedPersister.createNewEntry(embeddedPersister.getEntityFamily());
}
final PersistentEntity associatedEntity = association.getAssociatedEntity();
if (associatedEntity != null) {
final List<PersistentProperty> embeddedProperties = associatedEntity.getPersistentProperties();
final EntityAccess embeddedEntityAccess = createEntityAccess(associatedEntity, embeddedInstance);
PersistentProperty identity = associatedEntity.getIdentity();
if(identity != null) {
Object embeddedId = embeddedEntityAccess.getProperty(identity.getName());
if(embeddedId != null) {
setEntryValue(embeddedEntry, getPropertyKey(identity), embeddedId);
}
}
for (PersistentProperty persistentProperty : embeddedProperties) {
if (persistentProperty instanceof Simple) {
setEntryValue(embeddedEntry, getPropertyKey(persistentProperty), embeddedEntityAccess.getProperty(persistentProperty.getName()));
}
else if (persistentProperty instanceof Custom) {
Custom custom = (Custom)persistentProperty;
handleCustom(custom, embeddedEntityAccess, embeddedEntry);
}
else if (persistentProperty instanceof Association) {
if(persistentProperty instanceof Embedded) {
Association toOne = (Association) persistentProperty;
handleEmbeddedToOne(toOne,getPropertyKey(persistentProperty) , embeddedEntityAccess, embeddedEntry);
}
else if (persistentProperty instanceof ToOne) {
Association toOne = (Association) persistentProperty;
Object obj = embeddedEntityAccess.getProperty(toOne.getName());
Persister persister = getSession().getPersister(obj);
if(persister != null) {
Serializable id = persister.persist(obj);
if(id != null) {
setEntryValue(embeddedEntry, getPropertyKey(toOne), formulateDatabaseReference(embeddedPersister.getPersistentEntity(), association, id));
}
}
}
else if(persistentProperty instanceof Basic) {
setEntryValue(embeddedEntry, getPropertyKey(persistentProperty), embeddedEntityAccess.getProperty(persistentProperty.getName()));
}
else if(persistentProperty instanceof EmbeddedCollection) {
handleEmbeddedToMany(embeddedEntityAccess, embeddedEntry, persistentProperty, persistentProperty.getName());
}
else {
if (persistentProperty instanceof OneToMany) {
final OneToMany oneToMany = (OneToMany) persistentProperty;
final Object propValue = embeddedEntityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
List<Serializable> keys = session.persist(associatedObjects);
setEmbeddedCollectionKeys(oneToMany, embeddedEntityAccess, embeddedEntry, keys);
}
}
else if (persistentProperty instanceof ManyToMany) {
final ManyToMany manyToMany = (ManyToMany) persistentProperty;
final Object propValue = embeddedEntityAccess.getProperty(manyToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
List<Serializable> keys = session.persist(associatedObjects);
setManyToMany(embeddedPersister.getPersistentEntity(), embeddedInstance, embeddedEntry, manyToMany, associatedObjects, Collections.<Association, List<Serializable>>emptyMap());
}
}
}
}
}
}
return embeddedEntry;
}
private void handleIndexing(boolean update, T e, Map<PersistentProperty, Object> toIndex,
Map<PersistentProperty, Object> toUnindex, PersistentProperty prop, String key,
boolean indexed, Object propValue) {
if (!indexed) {
return;
}
if (update) {
final Object oldValue = getEntryValue(e, key);
boolean unindex = oldValue == null
? propValue != null
: !oldValue.equals(propValue);
if (unindex) {
toUnindex.put(prop, oldValue);
}
}
toIndex.put(prop, propValue);
}
protected boolean isPropertyIndexed(Property mappedProperty) {
return mappedProperty != null && mappedProperty.isIndex();
}
protected void setManyToMany(PersistentEntity persistentEntity, Object obj,
T nativeEntry, ManyToMany manyToMany, Collection associatedObjects,
Map<Association, List<Serializable>> toManyKeys) {
// override as necessary
}
/**
* Implementors should override this method to provide support for embedded objects
*
* @param nativeEntry The native entry
* @param key The key
* @param embeddedEntry The embedded object
*/
protected void setEmbedded(T nativeEntry, String key, T embeddedEntry) {
// do nothing. The default is no support for embedded instances
}
/**
* Implementors should override this method to provide support for embedded objects
*
* @param nativeEntry The native entry
* @param key The key
* @param instances the embedded instances
* @param embeddedEntries the native entries
*/
protected void setEmbeddedCollection(T nativeEntry, String key, Collection<?> instances, List<T> embeddedEntries) {
// do nothing. The default is no support for embedded collections
}
/**
* Subclasses should override to provide id generation. If an identifier is only generated via an insert operation then this
* method should return null
*
* @param persistentEntity The entity
* @param entry The native entry
* @return The identifier or null if an identifier is generated only on insert
*/
protected abstract K generateIdentifier(PersistentEntity persistentEntity, T entry);
private void updateToManyIndices(T nativeEntry, Object identifier, Map<Association, List<Serializable>> toManyKeys) {
// now cascade onto one-to-many associations
for (Association association : toManyKeys.keySet()) {
if (association.doesCascade(CascadeType.PERSIST)) {
final AssociationIndexer indexer = getAssociationIndexer(nativeEntry, association);
if (indexer != null) {
indexer.index(identifier, toManyKeys.get(association));
}
}
}
}
private void updatePropertyIndices(Object identifier, Map<PersistentProperty, Object> valuesToIndex, Map<PersistentProperty, Object> valuesToDeindex) {
// Here we manually create indices for any indexed properties so that queries work
for (PersistentProperty persistentProperty : valuesToIndex.keySet()) {
Object value = valuesToIndex.get(persistentProperty);
final PropertyValueIndexer indexer = getPropertyIndexer(persistentProperty);
if (indexer != null) {
indexer.index(value, identifier);
}
}
for (PersistentProperty persistentProperty : valuesToDeindex.keySet()) {
final PropertyValueIndexer indexer = getPropertyIndexer(persistentProperty);
Object value = valuesToDeindex.get(persistentProperty);
if (indexer != null) {
indexer.deindex(value, identifier);
}
}
}
/**
* Obtains an indexer for a particular property
*
* @param property The property to index
* @return The indexer
*/
public abstract PropertyValueIndexer getPropertyIndexer(PersistentProperty property);
/**
* Obtains an indexer for the given association
*
*
* @param nativeEntry The native entry
* @param association The association
* @return An indexer
*/
public abstract AssociationIndexer getAssociationIndexer(T nativeEntry, Association association);
/**
* Reads an objects identifier using the entity access and ClassMapping instance
* @param entityAccess
* @param cm
* @return The object identifier
*/
protected K readObjectIdentifier(EntityAccess entityAccess, ClassMapping cm) {
return (K) entityAccess.getIdentifier();
}
/**
* Obtains the identifier name to use. Subclasses can override to provide their own strategy for looking up an identifier name
* @param cm The ClassMapping instance
* @return The identifier name
*/
protected String getIdentifierName(ClassMapping cm) {
return cm.getIdentifier().getIdentifierName()[0];
}
/**
* This is a rather simplistic and unoptimized implementation. Subclasses can override to provide
* batch insert capabilities to optimize the insertion of multiple entities in one go
*
* @param persistentEntity The persistent entity
* @param objs The objext to persist
* @return A list of keys
*/
@Override
protected List<Serializable> persistEntities(PersistentEntity persistentEntity, Iterable objs) {
List<Serializable> keys = new ArrayList<Serializable>();
Iterable newIter = objs;
if(objs instanceof Collection) {
newIter = new ArrayList((Collection) objs);
}
for (Object obj : newIter) {
if(persistentEntity.isInstance(obj)) {
if(persistentEntity.getJavaClass().equals(obj.getClass())) {
keys.add(persist(obj));
}
else {
// subclass persister
EntityPersister persister = (EntityPersister) getSession().getPersister(obj);
keys.add(persister.persist(obj));
}
}
}
return keys;
}
/**
* Simplistic default implementation of retrieveAllEntities that iterates over each key and retrieves the entities
* one-by-one. Data stores that support batch retrieval can optimize this to retrieve all entities in one go.
*
* @param persistentEntity The persist entity
* @param keys The keys
* @return A list of entities
*/
@Override
protected List<Object> retrieveAllEntities(PersistentEntity persistentEntity, Iterable<Serializable> keys) {
List<Object> results = new ArrayList<Object>();
for (Serializable key : keys) {
results.add(retrieveEntity(persistentEntity, key));
}
return results;
}
/**
* Simplistic default implementation of retrieveAllEntities that iterates over each key and retrieves the entities
* one-by-one. Data stores that support batch retrieval can optimize this to retrieve all entities in one go.
*
* @param persistentEntity The persist entity
* @param keys The keys
* @return A list of entities
*/
@Override
protected List<Object> retrieveAllEntities(PersistentEntity persistentEntity, Serializable[] keys) {
List<Object> results = new ArrayList<Object>();
for (Serializable key : keys) {
results.add(retrieveEntity(persistentEntity, key));
}
return results;
}
/**
* Used to establish the native key to use from the identifier defined by the object
* @param family The family
* @param identifier The identifier specified by the object
* @return The native key which may just be a cast from the identifier parameter to K
*/
protected Object inferNativeKey(String family, Object identifier) {
return identifier;
}
/**
* Creates a new entry for the given family.
*
* @param family The family
* @return An entry such as a BigTable Entity, ColumnFamily etc.
*/
protected abstract T createNewEntry(String family);
/**
* Reads a value for the given key from the native entry
*
* @param nativeEntry The native entry. Could be a ColumnFamily, a BigTable entity, a Map etc.
* @param property The property key
* @return The value
*/
protected abstract Object getEntryValue(T nativeEntry, String property);
/**
* Sets a value on an entry
* @param nativeEntry The native entry such as a BigTable Entity, ColumnFamily etc.
* @param key The key
* @param value The value
*/
protected abstract void setEntryValue(T nativeEntry, String key, Object value);
/**
* Reads the native form of a Key/value datastore entry. This could be
* a ColumnFamily, a BigTable Entity, a Map etc.
*
* @param persistentEntity The persistent entity
* @param family The family
* @param key The key
* @return The native form
*/
protected abstract T retrieveEntry(PersistentEntity persistentEntity, String family, Serializable key);
/**
* Stores the native form of a Key/value datastore to the actual data store
*
* @param persistentEntity The persistent entity
* @param entityAccess The EntityAccess
* @param storeId
* @param nativeEntry The native form. Could be a a ColumnFamily, BigTable Entity etc.
* @return The native key
*/
protected abstract K storeEntry(PersistentEntity persistentEntity, EntityAccess entityAccess,
K storeId, T nativeEntry);
/**
* Updates an existing entry to the actual datastore
*
* @param persistentEntity The PersistentEntity
* @param entityAccess The EntityAccess
* @param key The key of the object to update
* @param entry The entry
*/
protected abstract void updateEntry(PersistentEntity persistentEntity,
EntityAccess entityAccess, K key, T entry);
/**
* Deletes one or many entries for the given list of Keys
*
* @param family The family
* @param keys The keys
*/
protected abstract void deleteEntries(String family, List<K> keys);
/**
* Executes an insert for the given entity, entity access, identifier and native entry.
* Any before interceptors will be triggered
*
* @param persistentEntity
* @param entityAccess
* @param id
* @param e
* @return The key
*/
protected K executeInsert(final PersistentEntity persistentEntity,
final NativeEntryModifyingEntityAccess entityAccess,
final K id, final T e) {
if (cancelInsert(persistentEntity, entityAccess)) return null;
final K newId = storeEntry(persistentEntity, entityAccess, id, e);
entityAccess.setIdentifier(newId);
updateTPCache(persistentEntity, e, (Serializable) newId);
firePostInsertEvent(persistentEntity, entityAccess);
return newId;
}
protected void updateTPCache(PersistentEntity persistentEntity, T e, Serializable id) {
if (cacheAdapterRepository == null) {
return;
}
TPCacheAdapter<T> cacheAdapter = cacheAdapterRepository.getTPCacheAdapter(persistentEntity);
if (cacheAdapter != null) {
cacheAdapter.cacheEntry(id, e);
}
}
protected T getFromTPCache(PersistentEntity persistentEntity, Serializable id) {
if (cacheAdapterRepository == null) {
return null;
}
TPCacheAdapter<T> cacheAdapter = cacheAdapterRepository.getTPCacheAdapter(persistentEntity);
if (cacheAdapter != null) {
return cacheAdapter.getCachedEntry(id);
}
return null;
}
protected class NativeEntryModifyingEntityAccess extends EntityAccess {
T nativeEntry;
private Map<PersistentProperty, Object> toIndex;
public NativeEntryModifyingEntityAccess(PersistentEntity persistentEntity, Object entity) {
super(persistentEntity, entity);
}
@Override
public void setProperty(String name, Object value) {
super.setProperty(name, value);
if (nativeEntry != null) {
PersistentProperty property = persistentEntity.getPropertyByName(name);
if (property != null && (property instanceof Simple)) {
setEntryValue(nativeEntry, name, value);
}
if(toIndex != null && property != null) {
PropertyMapping<Property> pm = property.getMapping();
if(pm != null && isPropertyIndexed(pm.getMappedForm())) {
if(property instanceof ToOne) {
ToOne association = (ToOne) property;
if(!association.isForeignKeyInChild()) {
NativeEntryEntityPersister associationPersister = (NativeEntryEntityPersister) session.getPersister(value);
if(value != null) {
toIndex.put(property, associationPersister.getObjectIdentifier(value));
}
else {
toIndex.put(property, null);
}
}
}
else {
toIndex.put(property, value);
}
}
}
}
}
public void setNativeEntry(T nativeEntry) {
this.nativeEntry = nativeEntry;
}
public void setToIndex(Map<PersistentProperty, Object> toIndex) {
this.toIndex = toIndex;
}
}
public boolean isDirty(Object instance, Object entry) {
if ((instance == null)) {
return false;
}
else if(entry == null) {
return true;
}
T nativeEntry;
try {
nativeEntry = (T)entry;
}
catch (ClassCastException ignored) {
return false;
}
EntityAccess entityAccess = createEntityAccess(getPersistentEntity(), instance, nativeEntry);
List<PersistentProperty> props = getPersistentEntity().getPersistentProperties();
for (PersistentProperty prop : props) {
String key = getPropertyKey(prop);
Object currentValue = entityAccess.getProperty(prop.getName());
Object oldValue = getEntryValue(nativeEntry, key);
if (prop instanceof Simple || prop instanceof Basic || prop instanceof ToOne ) {
if (!areEqual(oldValue, currentValue, key)) {
return true;
}
}
else if (prop instanceof OneToMany || prop instanceof ManyToMany) {
if (!areCollectionsEqual(oldValue, currentValue)) {
return true;
}
}
else if (prop instanceof EmbeddedCollection) {
if(currentValue != null && oldValue == null) return true;
if((currentValue instanceof Collection) && (oldValue instanceof Collection)) {
Collection currentCollection = (Collection) currentValue;
Collection oldCollection = (Collection) oldValue;
if(currentCollection.size() != oldCollection.size()) {
return true;
}
else {
if(!areCollectionsEqual(oldValue, currentValue)) {
return true;
}
}
}
}
else if (prop instanceof Custom) {
CustomTypeMarshaller marshaller = ((Custom)prop).getCustomTypeMarshaller();
return !areEqual(marshaller.read(prop, entry), currentValue, key);
}
else {
throw new UnsupportedOperationException("dirty not detected for property " + prop.toString() + " " + prop.getClass().getSuperclass().toString());
}
}
return false;
}
protected String getPropertyKey(PersistentProperty prop) {
PropertyMapping<Property> pm = prop.getMapping();
Property mappedProperty = pm.getMappedForm();
String key = null;
if (mappedProperty != null) {
key = mappedProperty.getTargetName();
}
if (key == null) key = prop.getName();
return key;
}
protected boolean areCollectionsEqual(Object oldValue, Object currentValue) {
if (oldValue == currentValue) {
// same or both null
return true;
}
if (currentValue instanceof PersistentCollection) {
return !((PersistentCollection)currentValue).isDirty();
}
return replaceNullOrUninitialized(oldValue, currentValue).equals(
replaceNullOrUninitialized(currentValue, oldValue));
}
private Object replaceNullOrUninitialized(Object c, Object other) {
if (c == null) {
if (other instanceof Set) {
return Collections.emptySet();
}
return Collections.emptyList();
}
if (c instanceof PersistentCollection && !((PersistentCollection)c).isInitialized()) {
if (c instanceof Set) {
return Collections.emptySet();
}
return Collections.emptyList();
}
return c;
}
protected boolean areEqual(Object oldValue, Object currentValue, String propName) {
if (oldValue == currentValue) {
return true;
}
if (oldValue == null || currentValue == null) {
return false;
}
if ("version".equals(propName)) {
// special case where comparing int and long would fail artifically
if (oldValue instanceof Number && currentValue instanceof Number) {
oldValue = ((Number)oldValue).longValue();
currentValue = ((Number)currentValue).longValue();
}
else {
oldValue = oldValue.toString();
currentValue = currentValue.toString();
}
}
Class oldValueClass = oldValue.getClass();
if (!oldValueClass.isArray()) {
if (oldValue instanceof Float) {
return Float.floatToIntBits((Float)oldValue) == Float.floatToIntBits((Float)currentValue);
}
if (oldValue instanceof Double) {
return Double.doubleToLongBits((Double)oldValue) == Double.doubleToLongBits((Double)currentValue);
}
return oldValue.equals(currentValue);
}
// check arrays
if (oldValue.getClass() != currentValue.getClass()) {
// different dimension
return false;
}
if (oldValue instanceof long[]) {
return Arrays.equals((long[])oldValue, (long[])currentValue);
}
if (oldValue instanceof int[]) {
return Arrays.equals((int[])oldValue, (int[])currentValue);
}
if (oldValue instanceof short[]) {
return Arrays.equals((short[])oldValue, (short[])currentValue);
}
if (oldValue instanceof char[]) {
return Arrays.equals((char[])oldValue, (char[])currentValue);
}
if (oldValue instanceof byte[]) {
return Arrays.equals((byte[])oldValue, (byte[])currentValue);
}
if (oldValue instanceof double[]) {
return Arrays.equals((double[])oldValue, (double[])currentValue);
}
if (oldValue instanceof float[]) {
return Arrays.equals((float[])oldValue, (float[])currentValue);
}
if (oldValue instanceof boolean[]) {
return Arrays.equals((boolean[])oldValue, (boolean[])currentValue);
}
return Arrays.equals((Object[])oldValue, (Object[])currentValue);
}
}
| false | true | protected final Serializable persistEntity(final PersistentEntity persistentEntity, Object obj) {
T tmp = null;
final NativeEntryModifyingEntityAccess entityAccess = (NativeEntryModifyingEntityAccess) createEntityAccess(persistentEntity, obj, tmp);
K k = readObjectIdentifier(entityAccess, persistentEntity.getMapping());
boolean isUpdate = k != null;
boolean assignedId = false;
if (isUpdate && !getSession().isDirty(obj)) {
return (Serializable) k;
}
PendingOperation<T, K> pendingOperation;
PropertyMapping mapping = persistentEntity.getIdentity().getMapping();
if(mapping != null) {
Property p = (Property) mapping.getMappedForm();
assignedId = p != null && "assigned".equals(p.getGenerator());
if(assignedId) {
if(isUpdate && !session.contains(obj)) {
isUpdate = false;
}
}
}
String family = getEntityFamily();
SessionImplementor<Object> si = (SessionImplementor<Object>) session;
if (!isUpdate) {
tmp = createNewEntry(family);
if(!assignedId)
k = generateIdentifier(persistentEntity, tmp);
cacheNativeEntry(persistentEntity, (Serializable) k, tmp);
pendingOperation = new PendingInsertAdapter<T, K>(persistentEntity, k, tmp, entityAccess) {
public void run() {
executeInsert(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
}
};
entityAccess.setProperty(entityAccess.getIdentifierName(), k);
}
else {
tmp = (T) si.getCachedEntry(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = getFromTPCache(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = retrieveEntry(persistentEntity, family, (Serializable) k);
}
}
if (tmp == null) {
tmp = createNewEntry(family);
}
final T finalTmp = tmp;
final K finalK = k;
pendingOperation = new PendingUpdateAdapter<T, K>(persistentEntity, finalK, finalTmp, entityAccess) {
public void run() {
if (cancelUpdate(persistentEntity, entityAccess)) return;
updateEntry(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
updateTPCache(persistentEntity, finalTmp, (Serializable) finalK);
firePostUpdateEvent(persistentEntity, entityAccess);
}
};
}
final T e = tmp;
entityAccess.setNativeEntry(e);
final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
final Map<Association, List<Serializable>> toManyKeys = new HashMap<Association, List<Serializable>>();
final Map<OneToMany, Serializable> inverseCollectionUpdates = new HashMap<OneToMany, Serializable>();
final Map<PersistentProperty, Object> toIndex = new HashMap<PersistentProperty, Object>();
final Map<PersistentProperty, Object> toUnindex = new HashMap<PersistentProperty, Object>();
entityAccess.setToIndex(toIndex);
for (PersistentProperty prop : props) {
PropertyMapping<Property> pm = prop.getMapping();
final Property mappedProperty = pm.getMappedForm();
String key = null;
if (mappedProperty != null) {
key = mappedProperty.getTargetName();
}
if (key == null) key = prop.getName();
final boolean indexed = isPropertyIndexed(mappedProperty);
if ((prop instanceof Simple) || (prop instanceof Basic)) {
Object propValue = entityAccess.getProperty(prop.getName());
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, propValue);
setEntryValue(e, key, propValue);
}
else if ((prop instanceof Custom)) {
CustomTypeMarshaller customTypeMarshaller = ((Custom) prop).getCustomTypeMarshaller();
if (customTypeMarshaller.supports(getSession().getDatastore())) {
Object propValue = entityAccess.getProperty(prop.getName());
Object customValue = customTypeMarshaller.write(prop, propValue, e);
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, customValue);
}
}
else if (prop instanceof OneToMany) {
final OneToMany oneToMany = (OneToMany) prop;
final Object propValue = entityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if (isInitializedCollection(associatedObjects)) {
EntityPersister associationPersister = (EntityPersister) session.getPersister(oneToMany.getAssociatedEntity());
if(associationPersister != null) {
PersistentCollection persistentCollection;
boolean newCollection = false;
if(associatedObjects instanceof PersistentCollection) {
persistentCollection = (PersistentCollection) associatedObjects;
}
else {
Class associationType = oneToMany.getAssociatedEntity().getJavaClass();
persistentCollection = getPersistentCollection(associatedObjects, associationType);
entityAccess.setProperty(oneToMany.getName(), persistentCollection);
persistentCollection.markDirty();
newCollection = true;
}
if(persistentCollection.isDirty()) {
persistentCollection.resetDirty();
List<Serializable> keys = associationPersister.persist(associatedObjects);
toManyKeys.put(oneToMany, keys);
if(newCollection ) {
entityAccess.setProperty(oneToMany.getName(), associatedObjects);
}
}
}
}
}
}
else if (prop instanceof ManyToMany) {
final ManyToMany manyToMany = (ManyToMany) prop;
final Object propValue = entityAccess.getProperty(manyToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if(isInitializedCollection(associatedObjects)) {
setManyToMany(persistentEntity, obj, e, manyToMany, associatedObjects, toManyKeys);
}
}
}
else if (prop instanceof ToOne) {
ToOne association = (ToOne) prop;
if (prop instanceof Embedded) {
// For embedded properties simply set the entry value, the underlying implementation
// will have to store the embedded entity in an appropriate way (as a sub-document in a document store for example)
handleEmbeddedToOne(association, key, entityAccess, e);
}
else if (association.doesCascade(CascadeType.PERSIST)) {
final Object associatedObject = entityAccess.getProperty(prop.getName());
if (associatedObject != null) {
@SuppressWarnings("hiding")
ProxyFactory proxyFactory = getProxyFactory();
// never cascade to proxies
if (proxyFactory.isInitialized(associatedObject)) {
Serializable associationId = null;
NativeEntryEntityPersister associationPersister = (NativeEntryEntityPersister) session.getPersister(associatedObject);
if (!session.contains(associatedObject)) {
Serializable tempId = associationPersister.getObjectIdentifier(associatedObject);
if (tempId == null) {
if (association.isOwningSide()) {
tempId = session.persist(associatedObject);
}
}
associationId = tempId;
}
else {
associationId = associationPersister.getObjectIdentifier(associatedObject);
}
// handling of hasOne inverse key
if (association.isForeignKeyInChild()) {
T cachedAssociationEntry = (T) si.getCachedEntry(association.getAssociatedEntity(), associationId);
if (cachedAssociationEntry != null) {
if (association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if (inverseSide != null) {
setEntryValue(cachedAssociationEntry, inverseSide.getName(), formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
else {
setEntryValue(cachedAssociationEntry, key, formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
}
}
if(association.doesCascade(CascadeType.PERSIST)) {
if(association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if(inverseSide != null) {
EntityAccess inverseAccess = new EntityAccess(inverseSide.getOwner(), associatedObject);
inverseAccess.setProperty(inverseSide.getName(), obj);
}
}
associationPersister.persist(associatedObject);
}
}
// handle of standard many-to-one
else {
if (associationId != null) {
if (indexed && doesRequirePropertyIndexing()) {
toIndex.put(prop, associationId);
if (isUpdate) {
Object oldValue = getEntryValue(e, key);
oldValue = oldValue != null ? convertToNativeKey( (Serializable) oldValue) : oldValue;
if (oldValue != null && !oldValue.equals(associationId)) {
toUnindex.put(prop, oldValue);
}
}
}
setEntryValue(e, key, formulateDatabaseReference(persistentEntity, association, associationId));
if (association.isBidirectional()) {
Association inverse = association.getInverseSide();
if (inverse instanceof OneToMany) {
inverseCollectionUpdates.put((OneToMany) inverse, associationId);
}
Object inverseEntity = entityAccess.getProperty(association.getName());
if (inverseEntity != null) {
EntityAccess inverseAccess = createEntityAccess(association.getAssociatedEntity(), inverseEntity);
if (inverse instanceof OneToMany) {
Collection existingValues = (Collection) inverseAccess.getProperty(inverse.getName());
if (existingValues == null) {
existingValues = MappingUtils.createConcreteCollection(inverse.getType());
inverseAccess.setProperty(inverse.getName(), existingValues);
}
existingValues.add(entityAccess.getEntity());
}
else if (inverse instanceof ToOne) {
inverseAccess.setProperty(inverse.getName(), entityAccess.getEntity());
}
}
}
}
}
}
}
else {
setEntryValue(e, getPropertyKey(prop), null);
}
}
}
else if (prop instanceof EmbeddedCollection) {
handleEmbeddedToMany(entityAccess, e, prop, key);
}
}
if (!isUpdate) {
// if the identifier is null at this point that means that datastore could not generated an identifer
// and the identifer is generated only upon insert of the entity
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
toIndex.put(persistentEntity.getIdentity(), updateId);
updatePropertyIndices(updateId, toIndex, toUnindex);
}
for (OneToMany inverseCollection : inverseCollectionUpdates.keySet()) {
final Serializable primaryKey = inverseCollectionUpdates.get(inverseCollection);
final NativeEntryEntityPersister inversePersister = (NativeEntryEntityPersister) session.getPersister(inverseCollection.getOwner());
final AssociationIndexer associationIndexer = inversePersister.getAssociationIndexer(e, inverseCollection);
associationIndexer.index(primaryKey, updateId);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
// If the key is still null at this point we have to execute the pending operation now to get the key
if (k == null) {
PendingOperationExecution.executePendingOperation(pendingOperation);
}
else {
si.addPendingInsert((PendingInsert) pendingOperation);
}
}
else {
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
updatePropertyIndices(updateId, toIndex, toUnindex);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
si.addPendingUpdate((PendingUpdate) pendingOperation);
}
return (Serializable) k;
}
| protected final Serializable persistEntity(final PersistentEntity persistentEntity, Object obj) {
T tmp = null;
final NativeEntryModifyingEntityAccess entityAccess = (NativeEntryModifyingEntityAccess) createEntityAccess(persistentEntity, obj, tmp);
K k = readObjectIdentifier(entityAccess, persistentEntity.getMapping());
boolean isUpdate = k != null;
boolean assignedId = false;
if (isUpdate && !getSession().isDirty(obj)) {
return (Serializable) k;
}
PendingOperation<T, K> pendingOperation;
PropertyMapping mapping = persistentEntity.getIdentity().getMapping();
if(mapping != null) {
Property p = (Property) mapping.getMappedForm();
assignedId = p != null && "assigned".equals(p.getGenerator());
if(assignedId) {
if(isUpdate && !session.contains(obj)) {
isUpdate = false;
}
}
}
String family = getEntityFamily();
SessionImplementor<Object> si = (SessionImplementor<Object>) session;
if (!isUpdate) {
tmp = createNewEntry(family);
if(!assignedId)
k = generateIdentifier(persistentEntity, tmp);
cacheNativeEntry(persistentEntity, (Serializable) k, tmp);
pendingOperation = new PendingInsertAdapter<T, K>(persistentEntity, k, tmp, entityAccess) {
public void run() {
executeInsert(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
}
};
entityAccess.setProperty(entityAccess.getIdentifierName(), k);
}
else {
tmp = (T) si.getCachedEntry(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = getFromTPCache(persistentEntity, (Serializable) k);
if (tmp == null) {
tmp = retrieveEntry(persistentEntity, family, (Serializable) k);
}
}
if (tmp == null) {
tmp = createNewEntry(family);
}
final T finalTmp = tmp;
final K finalK = k;
pendingOperation = new PendingUpdateAdapter<T, K>(persistentEntity, finalK, finalTmp, entityAccess) {
public void run() {
if (cancelUpdate(persistentEntity, entityAccess)) return;
updateEntry(persistentEntity, entityAccess, getNativeKey(), getNativeEntry());
updateTPCache(persistentEntity, finalTmp, (Serializable) finalK);
firePostUpdateEvent(persistentEntity, entityAccess);
}
};
}
final T e = tmp;
entityAccess.setNativeEntry(e);
final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
final Map<Association, List<Serializable>> toManyKeys = new HashMap<Association, List<Serializable>>();
final Map<OneToMany, Serializable> inverseCollectionUpdates = new HashMap<OneToMany, Serializable>();
final Map<PersistentProperty, Object> toIndex = new HashMap<PersistentProperty, Object>();
final Map<PersistentProperty, Object> toUnindex = new HashMap<PersistentProperty, Object>();
entityAccess.setToIndex(toIndex);
for (PersistentProperty prop : props) {
PropertyMapping<Property> pm = prop.getMapping();
final Property mappedProperty = pm.getMappedForm();
String key = null;
if (mappedProperty != null) {
key = mappedProperty.getTargetName();
}
if (key == null) key = prop.getName();
final boolean indexed = isPropertyIndexed(mappedProperty);
if ((prop instanceof Simple) || (prop instanceof Basic)) {
Object propValue = entityAccess.getProperty(prop.getName());
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, propValue);
setEntryValue(e, key, propValue);
}
else if ((prop instanceof Custom)) {
CustomTypeMarshaller customTypeMarshaller = ((Custom) prop).getCustomTypeMarshaller();
if (customTypeMarshaller.supports(getSession().getDatastore())) {
Object propValue = entityAccess.getProperty(prop.getName());
Object customValue = customTypeMarshaller.write(prop, propValue, e);
handleIndexing(isUpdate, e, toIndex, toUnindex, prop, key, indexed, customValue);
}
}
else if (prop instanceof OneToMany) {
final OneToMany oneToMany = (OneToMany) prop;
final Object propValue = entityAccess.getProperty(oneToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if (isInitializedCollection(associatedObjects)) {
EntityPersister associationPersister = (EntityPersister) session.getPersister(oneToMany.getAssociatedEntity());
if(associationPersister != null) {
PersistentCollection persistentCollection;
boolean newCollection = false;
if(associatedObjects instanceof PersistentCollection) {
persistentCollection = (PersistentCollection) associatedObjects;
}
else {
Class associationType = oneToMany.getAssociatedEntity().getJavaClass();
persistentCollection = getPersistentCollection(associatedObjects, associationType);
entityAccess.setProperty(oneToMany.getName(), persistentCollection);
persistentCollection.markDirty();
newCollection = true;
}
if(persistentCollection.isDirty()) {
persistentCollection.resetDirty();
List<Serializable> keys = associationPersister.persist(associatedObjects);
toManyKeys.put(oneToMany, keys);
if(newCollection ) {
entityAccess.setProperty(oneToMany.getName(), associatedObjects);
}
}
}
}
}
}
else if (prop instanceof ManyToMany) {
final ManyToMany manyToMany = (ManyToMany) prop;
final Object propValue = entityAccess.getProperty(manyToMany.getName());
if (propValue instanceof Collection) {
Collection associatedObjects = (Collection) propValue;
if(isInitializedCollection(associatedObjects)) {
setManyToMany(persistentEntity, obj, e, manyToMany, associatedObjects, toManyKeys);
}
}
}
else if (prop instanceof ToOne) {
ToOne association = (ToOne) prop;
if (prop instanceof Embedded) {
// For embedded properties simply set the entry value, the underlying implementation
// will have to store the embedded entity in an appropriate way (as a sub-document in a document store for example)
handleEmbeddedToOne(association, key, entityAccess, e);
}
else if (association.doesCascade(CascadeType.PERSIST)) {
final Object associatedObject = entityAccess.getProperty(prop.getName());
if (associatedObject != null) {
@SuppressWarnings("hiding")
ProxyFactory proxyFactory = getProxyFactory();
// never cascade to proxies
if (proxyFactory.isInitialized(associatedObject)) {
Serializable associationId = null;
NativeEntryEntityPersister associationPersister = (NativeEntryEntityPersister) session.getPersister(associatedObject);
if (!session.contains(associatedObject)) {
Serializable tempId = associationPersister.getObjectIdentifier(associatedObject);
if (tempId == null) {
if (association.isOwningSide()) {
tempId = session.persist(associatedObject);
}
}
associationId = tempId;
}
else {
associationId = associationPersister.getObjectIdentifier(associatedObject);
}
// handling of hasOne inverse key
if (association.isForeignKeyInChild()) {
T cachedAssociationEntry = (T) si.getCachedEntry(association.getAssociatedEntity(), associationId);
if (cachedAssociationEntry != null) {
if (association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if (inverseSide != null) {
setEntryValue(cachedAssociationEntry, inverseSide.getName(), formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
else {
setEntryValue(cachedAssociationEntry, key, formulateDatabaseReference(association.getAssociatedEntity(), inverseSide, (Serializable) k));
}
}
}
if(association.doesCascade(CascadeType.PERSIST)) {
if(association.isBidirectional()) {
Association inverseSide = association.getInverseSide();
if(inverseSide != null) {
EntityAccess inverseAccess = new EntityAccess(inverseSide.getOwner(), associatedObject);
inverseAccess.setProperty(inverseSide.getName(), obj);
}
}
associationPersister.persist(associatedObject);
}
}
// handle of standard many-to-one
else {
if (associationId != null) {
if (indexed && doesRequirePropertyIndexing()) {
toIndex.put(prop, associationId);
if (isUpdate) {
Object oldValue = getEntryValue(e, key);
oldValue = oldValue != null ? convertToNativeKey( (Serializable) oldValue) : oldValue;
if (oldValue != null && !oldValue.equals(associationId)) {
toUnindex.put(prop, oldValue);
}
}
}
setEntryValue(e, key, formulateDatabaseReference(persistentEntity, association, associationId));
if (association.isBidirectional()) {
Association inverse = association.getInverseSide();
if (inverse instanceof OneToMany) {
inverseCollectionUpdates.put((OneToMany) inverse, associationId);
}
Object inverseEntity = entityAccess.getProperty(association.getName());
if (inverseEntity != null) {
EntityAccess inverseAccess = createEntityAccess(association.getAssociatedEntity(), inverseEntity);
Object entity = entityAccess.getEntity();
if (inverse instanceof OneToMany) {
Collection existingValues = (Collection) inverseAccess.getProperty(inverse.getName());
if (existingValues == null) {
existingValues = MappingUtils.createConcreteCollection(inverse.getType());
inverseAccess.setProperty(inverse.getName(), existingValues);
}
if(!existingValues.contains(entity))
existingValues.add(entity);
}
else if (inverse instanceof ToOne) {
inverseAccess.setProperty(inverse.getName(), entity);
}
}
}
}
}
}
}
else {
setEntryValue(e, getPropertyKey(prop), null);
}
}
}
else if (prop instanceof EmbeddedCollection) {
handleEmbeddedToMany(entityAccess, e, prop, key);
}
}
if (!isUpdate) {
// if the identifier is null at this point that means that datastore could not generated an identifer
// and the identifer is generated only upon insert of the entity
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
toIndex.put(persistentEntity.getIdentity(), updateId);
updatePropertyIndices(updateId, toIndex, toUnindex);
}
for (OneToMany inverseCollection : inverseCollectionUpdates.keySet()) {
final Serializable primaryKey = inverseCollectionUpdates.get(inverseCollection);
final NativeEntryEntityPersister inversePersister = (NativeEntryEntityPersister) session.getPersister(inverseCollection.getOwner());
final AssociationIndexer associationIndexer = inversePersister.getAssociationIndexer(e, inverseCollection);
associationIndexer.index(primaryKey, updateId);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
// If the key is still null at this point we have to execute the pending operation now to get the key
if (k == null) {
PendingOperationExecution.executePendingOperation(pendingOperation);
}
else {
si.addPendingInsert((PendingInsert) pendingOperation);
}
}
else {
final K updateId = k;
PendingOperation postOperation = new PendingOperationAdapter<T, K>(persistentEntity, k, e) {
public void run() {
updateToManyIndices(e, updateId, toManyKeys);
if (doesRequirePropertyIndexing()) {
updatePropertyIndices(updateId, toIndex, toUnindex);
}
}
};
pendingOperation.addCascadeOperation(postOperation);
si.addPendingUpdate((PendingUpdate) pendingOperation);
}
return (Serializable) k;
}
|
diff --git a/app/models/Paster.java b/app/models/Paster.java
index 2dc8fca..4a7f958 100755
--- a/app/models/Paster.java
+++ b/app/models/Paster.java
@@ -1,193 +1,194 @@
package models;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import play.db.jpa.Model;
import play.modules.search.Field;
import play.modules.search.Indexed;
import play.modules.search.Query;
import play.modules.search.Search;
import util.TokenUtil;
import ys.wikiparser.WikiParser;
@Entity
@Indexed
public class Paster extends Model {
@Field
public String content;
public String wiki;
@Field(tokenize=true)
public String title;
@OneToOne
public Paster parent ;
@OneToOne
public Paster best;
@OneToOne
public User creator;
public Date created;
public Type type = Type.Q;
public String tagstext;
@ManyToMany
public Set<Tag> tags = new HashSet<Tag>();
@OneToOne
public User lastUser;
public Date updated;
public State state = State.NORMAL;
public int voteup;
public int votedown;
public int answerCount;
public int commentCount;
@OneToOne
public User lastAnswerUser;
@OneToOne(fetch=FetchType.LAZY)
public Paster lastAnswer;
public Date lastAnswered;
public static enum Type{
Q,A,C
}
public static enum State{
NORMAL,HIDDEN
}
public static Paster comment(long parentId,String content,User user) {
return createAndSave(null,content, user,null, -1,parentId,Type.C,false);
}
public static Paster answer(long parentId,String content,User user) {
return createAndSave(null,content, user,null, -1,parentId,Type.A,true);
}
public static Paster create(String title,String content,User user,String tags) {
return createAndSave(title,content, user,tags, -1,-1,Type.Q,true);
}
public static Paster update(long id ,String title,String content,User user,String tags) {
return createAndSave(title,content, user,tags, id,-1,null,true);
}
public static Paster createAndSave(String title,String content,User user,String tagstext,long id,long parentId,Type type,boolean wiki) {
Paster paster = null;
if(id > 0) {
paster = Paster.findById(id);
paster.lastUser = user;
paster.updated = new Date();
} else {
paster = new Paster();
paster.created= new Date();
paster.type = type;
paster.creator = user;
}
paster.wiki = content;
if(wiki)
paster.content = WikiParser.renderXHTML(paster.wiki);
else
paster.content = Jsoup.clean(paster.wiki,Whitelist.none());
//PasterUtil.cleanUpAndConvertImages(content, user.email);
//paster.content = content;
paster.title = title;
paster.tagstext = tagstext;
if(paster.tagstext!=null) {
String[] tagNames = tagstext.trim().split("[ ,;]");
for (String tag : tagNames) {
if(StringUtils.isNotEmpty(tag)) {
paster.tagWith(tag);
}
}
}
if(parentId>0) {
Paster tmp_parent = Paster.findById(parentId);
paster.parent = tmp_parent;
if(type== Type.C)
paster.parent.commentCount++;
if(type == Type.A) {
paster.parent.answerCount++;
paster.parent.lastAnswerUser = user;
paster.parent.lastAnswer = paster;
paster.parent.lastAnswered = new Date();
}
}
paster.save();
- paster.parent.save();
+ if(parentId >0)
+ paster.parent.save();
return paster;
}
public Paster tagWith(String tag) {
this.tags.add(Tag.findOrCreateByName(tag));
return this;
}
public static long countByCreator(String email){
return Paster.count("byCreator", email);
}
public static List<Paster> findByCreator(String email,int from,int pagesize){
JPAQuery find = Paster.find("creator=? order by createDate desc",email);
if(from>0)
find.from(from);
return find.fetch(pagesize);
}
public static List<Paster> findAll(int from ,int pagesize){
return findAll(from, pagesize,"order by createDate desc");
}
public static List<Paster> findMostUseful(int from ,int pagesize){
return findAll(from, pagesize,"order by useful desc");
}
public static List<Paster> findAll(int from ,int pagesize,String order){
return Paster.find(order).from(from).fetch(pagesize);
}
public static List<Paster> findAll(int from ,int pagesize,String query,String order){
return Paster.find(query +" " + order).from(from).fetch(pagesize);
}
public void remove() {
delete();
}
public void voteup() {
voteup+=1;
save();
}
public void votedown() {
votedown+=1;
save();
}
public static class QueryResult{
public long count;
public List<Paster> results;
public QueryResult(List<Paster> list,long count) {
this.results = list;
this.count = count;
}
}
public static QueryResult search(String keywords, int from, int pagesize) {
String query = "content:(" + StringUtils.join(TokenUtil.token(keywords), " AND ")+")";
query += " OR title:(" + StringUtils.join(TokenUtil.token(keywords), " AND ")+")";
Query q = Search.search(query, Paster.class);
q.orderBy("title").page(from * pagesize, pagesize).reverse();
List<Paster> fetch = q.fetch();
return new QueryResult(fetch, q.count());
}
public List<Paster> getAnswers() {
return Paster.find("state = ? and parent.id = ? and type=?", State.NORMAL,this.id,Type.A).fetch();
}
public List<Paster> getComments() {
return Paster.find("state = ? and parent.id= ? and type=?", State.NORMAL, this.id,Type.C).fetch();
}
public void hide() {
this.state = State.HIDDEN;
if(parent!=null && this.type == Type.A) {
parent.answerCount--;
parent.save();
}
if(parent!=null && this.type == Type.C) {
parent.commentCount--;
parent.save();
}
save();
}
}
| true | true | public static Paster createAndSave(String title,String content,User user,String tagstext,long id,long parentId,Type type,boolean wiki) {
Paster paster = null;
if(id > 0) {
paster = Paster.findById(id);
paster.lastUser = user;
paster.updated = new Date();
} else {
paster = new Paster();
paster.created= new Date();
paster.type = type;
paster.creator = user;
}
paster.wiki = content;
if(wiki)
paster.content = WikiParser.renderXHTML(paster.wiki);
else
paster.content = Jsoup.clean(paster.wiki,Whitelist.none());
//PasterUtil.cleanUpAndConvertImages(content, user.email);
//paster.content = content;
paster.title = title;
paster.tagstext = tagstext;
if(paster.tagstext!=null) {
String[] tagNames = tagstext.trim().split("[ ,;]");
for (String tag : tagNames) {
if(StringUtils.isNotEmpty(tag)) {
paster.tagWith(tag);
}
}
}
if(parentId>0) {
Paster tmp_parent = Paster.findById(parentId);
paster.parent = tmp_parent;
if(type== Type.C)
paster.parent.commentCount++;
if(type == Type.A) {
paster.parent.answerCount++;
paster.parent.lastAnswerUser = user;
paster.parent.lastAnswer = paster;
paster.parent.lastAnswered = new Date();
}
}
paster.save();
paster.parent.save();
return paster;
}
| public static Paster createAndSave(String title,String content,User user,String tagstext,long id,long parentId,Type type,boolean wiki) {
Paster paster = null;
if(id > 0) {
paster = Paster.findById(id);
paster.lastUser = user;
paster.updated = new Date();
} else {
paster = new Paster();
paster.created= new Date();
paster.type = type;
paster.creator = user;
}
paster.wiki = content;
if(wiki)
paster.content = WikiParser.renderXHTML(paster.wiki);
else
paster.content = Jsoup.clean(paster.wiki,Whitelist.none());
//PasterUtil.cleanUpAndConvertImages(content, user.email);
//paster.content = content;
paster.title = title;
paster.tagstext = tagstext;
if(paster.tagstext!=null) {
String[] tagNames = tagstext.trim().split("[ ,;]");
for (String tag : tagNames) {
if(StringUtils.isNotEmpty(tag)) {
paster.tagWith(tag);
}
}
}
if(parentId>0) {
Paster tmp_parent = Paster.findById(parentId);
paster.parent = tmp_parent;
if(type== Type.C)
paster.parent.commentCount++;
if(type == Type.A) {
paster.parent.answerCount++;
paster.parent.lastAnswerUser = user;
paster.parent.lastAnswer = paster;
paster.parent.lastAnswered = new Date();
}
}
paster.save();
if(parentId >0)
paster.parent.save();
return paster;
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/HeartbeatJob.java b/src/webapp/src/java/org/wyona/yanel/servlet/HeartbeatJob.java
index 671798d96..864b5abab 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/HeartbeatJob.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/HeartbeatJob.java
@@ -1,30 +1,30 @@
package org.wyona.yanel.servlet;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.apache.log4j.Logger;
import org.wyona.yanel.core.map.Realm;
/**
* Heartbeat job
*/
public class HeartbeatJob implements Job {
private static Logger log = Logger.getLogger(HeartbeatJob.class);
/**
*
*/
public void execute(JobExecutionContext context) throws JobExecutionException {
Realm realm = (Realm) context.getJobDetail().getJobDataMap().get("realm");
String realmName = null;
if (realm != null) {
realmName = realm.getName();
}
log.info("Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")"); // TODO: Show statistics, e.g. uptime, etc.
- //log.warn("DEBUG: Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")");
+ //log.debug("Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")");
}
}
| true | true | public void execute(JobExecutionContext context) throws JobExecutionException {
Realm realm = (Realm) context.getJobDetail().getJobDataMap().get("realm");
String realmName = null;
if (realm != null) {
realmName = realm.getName();
}
log.info("Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")"); // TODO: Show statistics, e.g. uptime, etc.
//log.warn("DEBUG: Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")");
}
| public void execute(JobExecutionContext context) throws JobExecutionException {
Realm realm = (Realm) context.getJobDetail().getJobDataMap().get("realm");
String realmName = null;
if (realm != null) {
realmName = realm.getName();
}
log.info("Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")"); // TODO: Show statistics, e.g. uptime, etc.
//log.debug("Heartbeat: " + new java.util.Date() + " (Realm: " + realmName + ")");
}
|
diff --git a/core/src/main/java/org/apache/ldap/server/authn/SimpleAuthenticator.java b/core/src/main/java/org/apache/ldap/server/authn/SimpleAuthenticator.java
index 33003a7b1e..d31abbeb51 100644
--- a/core/src/main/java/org/apache/ldap/server/authn/SimpleAuthenticator.java
+++ b/core/src/main/java/org/apache/ldap/server/authn/SimpleAuthenticator.java
@@ -1,134 +1,134 @@
/*
* Copyright 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.ldap.server.authn;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import org.apache.ldap.common.exception.LdapAuthenticationException;
import org.apache.ldap.common.name.LdapName;
import org.apache.ldap.common.util.ArrayUtils;
import org.apache.ldap.server.jndi.ServerContext;
import org.apache.ldap.server.partition.ContextPartitionNexus;
/**
* A simple {@link Authenticator} that authenticates clear text passwords
* contained within the <code>userPassword</code> attribute in DIT.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class SimpleAuthenticator extends AbstractAuthenticator
{
/**
* Creates a new instance.
*/
public SimpleAuthenticator( )
{
super( "simple" );
}
/**
* Looks up <tt>userPassword</tt> attribute of the entry whose name is
* the value of {@link Context#SECURITY_PRINCIPAL} environment variable,
* and authenticates a user with the plain-text password.
*/
public LdapPrincipal authenticate( ServerContext ctx ) throws NamingException
{
// ---- extract password from JNDI environment
Object creds = ctx.getEnvironment().get( Context.SECURITY_CREDENTIALS );
if ( creds == null )
{
creds = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else if ( creds instanceof String )
{
creds = ( ( String ) creds ).getBytes();
}
// ---- extract principal from JNDI environment
String principal;
if ( ! ctx.getEnvironment().containsKey( Context.SECURITY_PRINCIPAL ) )
{
throw new LdapAuthenticationException();
}
else
{
principal = ( String ) ctx.getEnvironment().get( Context.SECURITY_PRINCIPAL );
if ( principal == null )
{
throw new LdapAuthenticationException();
}
}
// ---- lookup the principal entry's userPassword attribute
LdapName principalDn = new LdapName( principal );
ContextPartitionNexus nexus = getFactoryConfiguration().getPartitionNexus();
Attributes userEntry;
try
{
- userEntry = nexus.lookup( principalDn );
+ userEntry = nexus.lookup( principalDn, new String[] {"userPassword"} );
if ( userEntry == null )
{
throw new LdapAuthenticationException();
}
}
catch( Exception e )
{
throw new LdapAuthenticationException();
}
Object userPassword;
Attribute userPasswordAttr = userEntry.get( "userPassword" );
// ---- assert that credentials match
if ( userPasswordAttr == null )
{
userPassword = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else
{
userPassword = userPasswordAttr.get();
if ( userPassword instanceof String )
{
userPassword = ( ( String ) userPassword ).getBytes();
}
}
if ( ! ArrayUtils.isEquals( creds, userPassword ) )
{
throw new LdapAuthenticationException();
}
return new LdapPrincipal( principalDn );
}
}
| true | true | public LdapPrincipal authenticate( ServerContext ctx ) throws NamingException
{
// ---- extract password from JNDI environment
Object creds = ctx.getEnvironment().get( Context.SECURITY_CREDENTIALS );
if ( creds == null )
{
creds = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else if ( creds instanceof String )
{
creds = ( ( String ) creds ).getBytes();
}
// ---- extract principal from JNDI environment
String principal;
if ( ! ctx.getEnvironment().containsKey( Context.SECURITY_PRINCIPAL ) )
{
throw new LdapAuthenticationException();
}
else
{
principal = ( String ) ctx.getEnvironment().get( Context.SECURITY_PRINCIPAL );
if ( principal == null )
{
throw new LdapAuthenticationException();
}
}
// ---- lookup the principal entry's userPassword attribute
LdapName principalDn = new LdapName( principal );
ContextPartitionNexus nexus = getFactoryConfiguration().getPartitionNexus();
Attributes userEntry;
try
{
userEntry = nexus.lookup( principalDn );
if ( userEntry == null )
{
throw new LdapAuthenticationException();
}
}
catch( Exception e )
{
throw new LdapAuthenticationException();
}
Object userPassword;
Attribute userPasswordAttr = userEntry.get( "userPassword" );
// ---- assert that credentials match
if ( userPasswordAttr == null )
{
userPassword = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else
{
userPassword = userPasswordAttr.get();
if ( userPassword instanceof String )
{
userPassword = ( ( String ) userPassword ).getBytes();
}
}
if ( ! ArrayUtils.isEquals( creds, userPassword ) )
{
throw new LdapAuthenticationException();
}
return new LdapPrincipal( principalDn );
}
| public LdapPrincipal authenticate( ServerContext ctx ) throws NamingException
{
// ---- extract password from JNDI environment
Object creds = ctx.getEnvironment().get( Context.SECURITY_CREDENTIALS );
if ( creds == null )
{
creds = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else if ( creds instanceof String )
{
creds = ( ( String ) creds ).getBytes();
}
// ---- extract principal from JNDI environment
String principal;
if ( ! ctx.getEnvironment().containsKey( Context.SECURITY_PRINCIPAL ) )
{
throw new LdapAuthenticationException();
}
else
{
principal = ( String ) ctx.getEnvironment().get( Context.SECURITY_PRINCIPAL );
if ( principal == null )
{
throw new LdapAuthenticationException();
}
}
// ---- lookup the principal entry's userPassword attribute
LdapName principalDn = new LdapName( principal );
ContextPartitionNexus nexus = getFactoryConfiguration().getPartitionNexus();
Attributes userEntry;
try
{
userEntry = nexus.lookup( principalDn, new String[] {"userPassword"} );
if ( userEntry == null )
{
throw new LdapAuthenticationException();
}
}
catch( Exception e )
{
throw new LdapAuthenticationException();
}
Object userPassword;
Attribute userPasswordAttr = userEntry.get( "userPassword" );
// ---- assert that credentials match
if ( userPasswordAttr == null )
{
userPassword = ArrayUtils.EMPTY_BYTE_ARRAY;
}
else
{
userPassword = userPasswordAttr.get();
if ( userPassword instanceof String )
{
userPassword = ( ( String ) userPassword ).getBytes();
}
}
if ( ! ArrayUtils.isEquals( creds, userPassword ) )
{
throw new LdapAuthenticationException();
}
return new LdapPrincipal( principalDn );
}
|
diff --git a/src/com/google/gwt/sample/stockwatcher/client/FlexTableDropController.java b/src/com/google/gwt/sample/stockwatcher/client/FlexTableDropController.java
index f6652e7..6de8eea 100644
--- a/src/com/google/gwt/sample/stockwatcher/client/FlexTableDropController.java
+++ b/src/com/google/gwt/sample/stockwatcher/client/FlexTableDropController.java
@@ -1,114 +1,114 @@
package com.google.gwt.sample.stockwatcher.client;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.drop.AbstractPositioningDropController;
import com.allen_sauer.gwt.dnd.client.util.CoordinateLocation;
import com.allen_sauer.gwt.dnd.client.util.DOMUtil;
import com.allen_sauer.gwt.dnd.client.util.Location;
import com.allen_sauer.gwt.dnd.client.util.LocationWidgetComparator;
import com.allen_sauer.gwt.dnd.client.util.WidgetLocation;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.InsertPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
public class FlexTableDropController extends AbstractPositioningDropController {
TemperatureWatcher parent;
private static final String CSS_DEMO_TABLE_POSITIONER = "demo-table-positioner";
private FlexTable flexTable;
private InsertPanel flexTableRowsAsIndexPanel = new InsertPanel() {
@Override
public void add(Widget w) {
throw new UnsupportedOperationException();
}
@Override
public Widget getWidget(int index) {
return flexTable.getWidget(index, 0);
}
@Override
public int getWidgetCount() {
return flexTable.getRowCount();
}
@Override
public int getWidgetIndex(Widget child) {
throw new UnsupportedOperationException();
}
@Override
public void insert(Widget w, int beforeIndex) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(int index) {
throw new UnsupportedOperationException();
}
};
private Widget positioner = null;
private int targetRow;
public FlexTableDropController(FlexTable flexTable) {
super(flexTable);
this.flexTable = flexTable;
}
@Override
public void onDrop(DragContext context) {
FlexTableDragController trDragController = (FlexTableDragController) context.dragController;
FlexTableUtil.moveRow(trDragController.getDraggableTable(), flexTable,
trDragController.getDragRow(), targetRow + 1);
super.onDrop(context);
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
positioner = newPositioner(context);
}
@Override
public void onLeave(DragContext context) {
positioner.removeFromParent();
positioner = null;
super.onLeave(context);
}
@Override
public void onMove(DragContext context) {
super.onMove(context);
targetRow = DOMUtil.findIntersect(flexTableRowsAsIndexPanel, new CoordinateLocation(
context.mouseX, context.mouseY), LocationWidgetComparator.BOTTOM_HALF_COMPARATOR) - 1;
if (flexTable.getRowCount() > 0) {
- Widget w = flexTable.getWidget(targetRow == -1 ? 0 : targetRow, 0);
+ Widget w = flexTable.getWidget(targetRow == -1 ? 0 : targetRow, 0); //TODO, cause of the nullpointer, w can be null
Location widgetLocation = new WidgetLocation(w, context.boundaryPanel);
Location tableLocation = new WidgetLocation(flexTable, context.boundaryPanel);
context.boundaryPanel.add(positioner, tableLocation.getLeft(), widgetLocation.getTop()
- + (targetRow == -1 ? 0 : w.getOffsetHeight()));
+ + (targetRow == -1 ? 0 : w.getOffsetHeight())); //TODO: fix nullpointer exception here
}
}
Widget newPositioner(DragContext context) {
Widget p = new SimplePanel();
p.addStyleName(CSS_DEMO_TABLE_POSITIONER);
p.setPixelSize(flexTable.getOffsetWidth(), 1);
return p;
}
}
| false | true | public void onMove(DragContext context) {
super.onMove(context);
targetRow = DOMUtil.findIntersect(flexTableRowsAsIndexPanel, new CoordinateLocation(
context.mouseX, context.mouseY), LocationWidgetComparator.BOTTOM_HALF_COMPARATOR) - 1;
if (flexTable.getRowCount() > 0) {
Widget w = flexTable.getWidget(targetRow == -1 ? 0 : targetRow, 0);
Location widgetLocation = new WidgetLocation(w, context.boundaryPanel);
Location tableLocation = new WidgetLocation(flexTable, context.boundaryPanel);
context.boundaryPanel.add(positioner, tableLocation.getLeft(), widgetLocation.getTop()
+ (targetRow == -1 ? 0 : w.getOffsetHeight()));
}
}
| public void onMove(DragContext context) {
super.onMove(context);
targetRow = DOMUtil.findIntersect(flexTableRowsAsIndexPanel, new CoordinateLocation(
context.mouseX, context.mouseY), LocationWidgetComparator.BOTTOM_HALF_COMPARATOR) - 1;
if (flexTable.getRowCount() > 0) {
Widget w = flexTable.getWidget(targetRow == -1 ? 0 : targetRow, 0); //TODO, cause of the nullpointer, w can be null
Location widgetLocation = new WidgetLocation(w, context.boundaryPanel);
Location tableLocation = new WidgetLocation(flexTable, context.boundaryPanel);
context.boundaryPanel.add(positioner, tableLocation.getLeft(), widgetLocation.getTop()
+ (targetRow == -1 ? 0 : w.getOffsetHeight())); //TODO: fix nullpointer exception here
}
}
|
diff --git a/app/controllers/FeatureController.java b/app/controllers/FeatureController.java
index a1fab8f..028833c 100644
--- a/app/controllers/FeatureController.java
+++ b/app/controllers/FeatureController.java
@@ -1,406 +1,418 @@
package controllers;
import com.avaje.ebean.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import models.*;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import java.sql.Timestamp;
import java.util.*;
@Security.Authenticated(Secured.class)
public class FeatureController extends Controller {
public static final double WEIGHT_ENG_COST = 2;
public static final double WEIGHT_REVENUE_BENEFIT = 3;
public static final double WEIGHT_RETENTION_BENEFIT = 1.5;
public static final double WEIGHT_POSITIONING_BENEFIT = 2.5;
public static final double MAX_SCORE = WEIGHT_ENG_COST * Size.NONE.getCostWeight() +
WEIGHT_REVENUE_BENEFIT * Size.XLARGE.getBenefitWeight() +
WEIGHT_RETENTION_BENEFIT * Size.XLARGE.getBenefitWeight() +
WEIGHT_POSITIONING_BENEFIT * Size.XLARGE.getBenefitWeight();
public static Result getFeature(Long id) {
Feature feature = Feature.find.byId(id);
if (feature == null) {
return notFound();
}
// get the tags
feature.tags = new HashSet<>();
SqlQuery query = Ebean.createSqlQuery("select tag from feature_tags where feature_id = :feature_id");
query.setParameter("feature_id", id);
List<SqlRow> list = query.findList();
for (SqlRow row : list) {
feature.tags.add(row.getString("tag"));
}
return ok(Json.toJson(dressFeature(feature)));
}
@play.db.ebean.Transactional
public static Result updateFeature(Long id) {
// Only `PM`s can update features
if (!Secured.checkRole(UserRole.PM)) {
return forbidden();
}
Feature original = Feature.find.byId(id);
if (original == null) {
return notFound();
}
JsonNode json = request().body().asJson();
Feature update = Json.fromJson(json, Feature.class);
original.assignee = update.assignee;
original.lastModified = new Timestamp(System.currentTimeMillis());
original.lastModifiedBy = User.findByEmail(request().username());
original.title = update.title;
original.title = update.title;
original.description = update.description;
original.state = update.state;
original.engineeringCost = update.engineeringCost;
original.revenueBenefit = update.revenueBenefit;
original.retentionBenefit = update.retentionBenefit;
original.positioningBenefit = update.positioningBenefit;
original.score = 0; // todo: do we even need this?
original.team = update.team;
original.quarter = update.quarter;
original.save();
// delete tag and then re-add
SqlUpdate delete = Ebean.createSqlUpdate("delete from feature_tags where feature_id = :feature_id");
delete.setParameter("feature_id", id);
delete.execute();
insertTags(update);
return ok(Json.toJson(dressFeature(original)));
}
public static Result bulkUpdate() {
JsonNode json = request().body().asJson();
FeatureBulkChange bulkChange = Json.fromJson(json, FeatureBulkChange.class);
if (bulkChange.ids == null || bulkChange.ids.size() == 0) {
return notFound();
}
if (bulkChange.assignee != null) {
if ("nobody".equals(bulkChange.assignee.email)) {
Ebean.createSqlUpdate("update feature set assignee_email = null where id in (:ids)")
.setParameter("ids", bulkChange.ids)
.execute();
} else {
Ebean.createSqlUpdate("update feature set assignee_email = :assignee where id in (:ids)")
.setParameter("assignee", bulkChange.assignee.email)
.setParameter("ids", bulkChange.ids)
.execute();
}
}
if (bulkChange.state != null) {
Ebean.createSqlUpdate("update feature set state = :state where id in (:ids)")
.setParameter("state", bulkChange.state)
.setParameter("ids", bulkChange.ids)
.execute();
}
if (bulkChange.team != null) {
if (bulkChange.team.id > 0) {
Ebean.createSqlUpdate("update feature set team_id = :team where id in (:ids)")
.setParameter("team", bulkChange.team.id)
.setParameter("ids", bulkChange.ids)
.execute();
} else {
Ebean.createSqlUpdate("update feature set team_id = null where id in (:ids)")
.setParameter("ids", bulkChange.ids)
.execute();
}
}
if (bulkChange.tags != null && !bulkChange.tags.isEmpty()) {
// delete the tags in case they already exist...
Ebean.createSqlUpdate("delete from feature_tags where feature_id in (:ids) and tag in (:tags)")
.setParameter("ids", bulkChange.ids)
.setParameter("tags", bulkChange.tags)
.execute();
// .. and now re-insert them
SqlUpdate tagInsert = Ebean.createSqlUpdate("insert into feature_tags (feature_id, tag) values (:id, :tag)");
for (String tag : bulkChange.tags) {
for (Long id : bulkChange.ids) {
tagInsert.setParameter("id", id).setParameter("tag", tag).execute();
}
}
}
return ok();
}
@play.db.ebean.Transactional
public static Result bulkDelete() {
JsonNode json = request().body().asJson();
FeatureBulkChange bulkChange = Json.fromJson(json, FeatureBulkChange.class);
if (bulkChange.ids == null || bulkChange.ids.size() == 0) {
return notFound();
}
for (Long id : bulkChange.ids) {
deleteFeature(id);
}
return ok();
}
public static Result find() {
if (!request().queryString().containsKey("query")) {
return ok();
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
return ok();
}
Integer limit = null;
if (request().queryString().get("limit") != null) {
limit = Integer.parseInt(request().queryString().get("limit")[0]);
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
Map<Long, Float> rankings = null;
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.eq("quarter", Integer.parseInt(term.substring(8)));
} else if (term.startsWith("assignedTo:")) {
+ String str = term.substring(11);
+ switch (str) {
+ case "null":
+ where.isNull("t0.assignee_email");
+ break;
+ case "not-null":
+ where.isNotNull("t0.assignee_email");
+ break;
+ default:
+ where.eq("t0.assignee_email", str);
+ break;
+ }
where.eq("assignee_email", term.substring(11));
} else if (term.startsWith("text:")) {
rankings = new HashMap<>();
String tsquery = term.substring(5);
tsquery = tsquery.replaceAll("[\\|\\&\\!']", "-")
.replaceAll("[ \t\n\r]", "|");
SqlQuery searchQuery = Ebean.createSqlQuery("select id, ts_rank_cd(textsearch, query) rank from (select id, setweight(to_tsvector(coalesce((select string_agg(tag, ' ') from feature_tags where feature_id = id),'')), 'A') || setweight(to_tsvector(coalesce(title,'')), 'B') || setweight(to_tsvector(coalesce(description,'')), 'C') as textsearch from feature) t, to_tsquery(:tsquery) query where textsearch @@ query order by rank desc");
searchQuery.setParameter("tsquery", tsquery);
if (limit != null) {
searchQuery.setMaxRows(limit);
}
List<SqlRow> list = searchQuery.findList();
for (SqlRow row : list) {
rankings.put(row.getLong("id"), row.getFloat("rank"));
}
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
if (limit != null) {
tagQuery.setMaxRows(limit);
}
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
if (rankings != null) {
if (rankings.isEmpty()) {
return ok();
}
where.in("id", rankings.keySet());
}
// fixes N+1 query problem
where.join("creator");
where.join("lastModifiedBy");
if (limit != null) {
where.setMaxRows(limit);
}
List<Feature> list = where.findList();
if (rankings != null) {
for (Feature feature : list) {
feature.rank = rankings.get(feature.id);
}
}
JsonNode jsonNode = Json.toJson(dressFeatures(list));
return ok(jsonNode);
}
public static Feature dressFeature(Feature feature) {
return dressFeatures(Collections.singletonList(feature)).get(0);
}
public static List<Feature> dressFeatures(List<Feature> features) {
// first, get all the feature IDs so we can get all problems in a single query
final Map<Long, Feature> featureMap = new HashMap<>();
for (Feature feature : features) {
featureMap.put(feature.id, feature);
// also calculate a score
double score = 0d;
score += WEIGHT_ENG_COST * (feature.engineeringCost == null ? 0 : feature.engineeringCost.getCostWeight());
score += WEIGHT_REVENUE_BENEFIT * (feature.revenueBenefit == null ? 0 : feature.revenueBenefit.getBenefitWeight());
score += WEIGHT_RETENTION_BENEFIT * (feature.retentionBenefit == null ? 0 : feature.retentionBenefit.getBenefitWeight());
score += WEIGHT_POSITIONING_BENEFIT * (feature.positioningBenefit == null ? 0 : feature.positioningBenefit.getBenefitWeight());
// normalize to max score
feature.score = (int) (score / MAX_SCORE * 100);
feature.problemCount = 0;
feature.problemRevenue = 0;
}
// now query all problems
List<Problem> problems = Problem.find.where().in("feature_id", featureMap.keySet()).findList();
for (Problem problem : problems) {
Feature feature = featureMap.get(problem.feature.id);
feature.problemCount++;
if (problem.annualRevenue != null) {
feature.problemRevenue += problem.annualRevenue;
}
}
return features;
}
public static Result create() {
// Only `PM`s can create features
if (!Secured.checkRole(UserRole.PM)) {
return forbidden();
}
JsonNode json = request().body().asJson();
Feature feature = Json.fromJson(json, Feature.class);
feature.lastModified = new Timestamp(System.currentTimeMillis());
feature.creator = feature.lastModifiedBy = User.findByEmail(request().username());
feature.state = FeatureState.OPEN;
feature.save();
insertTags(feature);
return ok(Json.toJson(dressFeature(feature)));
}
private static void insertTags(Feature feature) {
// now save the tags
if (feature.tags != null && !feature.tags.isEmpty()) {
SqlUpdate update = Ebean.createSqlUpdate("insert into feature_tags (feature_id, tag) values (:feature_id, :tag)");
for (String tag : feature.tags) {
update.setParameter("feature_id", feature.id);
update.setParameter("tag", tag);
update.execute();
}
}
}
@play.db.ebean.Transactional
public static Result deleteFeature(Long id) {
// Only `PM`s can delete features
if (!Secured.checkRole(UserRole.PM)) {
return forbidden();
}
Feature feature = Feature.find.ref(id);
// Make sure the feature exists before doing any updates
if (feature == null) {
return notFound();
}
// Check the options on the delete
JsonNode json = request().body().asJson();
if (json != null && json.findPath("copyTagsToProblems").asBoolean()) {
String copyFeatureTagsSql = "INSERT INTO problem_tags " +
"SELECT p.id, ft.tag " +
"FROM feature_tags ft, problem p " +
"WHERE ft.feature_id = :feature_id " +
"AND p.feature_id = :feature_id2 " +
"AND ft.tag NOT IN (SELECT tag FROM problem_tags WHERE problem_id = p.id)";
SqlUpdate copyTags = Ebean.createSqlUpdate(copyFeatureTagsSql);
copyTags.setParameter("feature_id", id);
copyTags.setParameter("feature_id2", id);
copyTags.execute();
}
Feature target = null;
if (json != null && json.findPath("featureForProblems").asLong(-1) != -1) {
// Move related problems to a new feature if the feature exists
Long targetId = json.findPath("featureForProblems").asLong();
target = Feature.find.ref(targetId);
}
if (target != null) {
// Associate related problems to target
SqlUpdate moveProblems = Ebean.createSqlUpdate("update problem set feature_id = :target_id where feature_id = :feature_id");
moveProblems.setParameter("feature_id", id);
moveProblems.setParameter("target_id", target.id);
moveProblems.execute();
}
else {
// Dissociate related problems
SqlUpdate dissociateProblems = Ebean.createSqlUpdate("update problem set feature_id = NULL where feature_id = :feature_id");
dissociateProblems.setParameter("feature_id", id);
dissociateProblems.execute();
}
// Delete the feature's tags
SqlUpdate deleteTags = Ebean.createSqlUpdate("delete from feature_tags where feature_id = :feature_id");
deleteTags.setParameter("feature_id", id);
deleteTags.execute();
// Delete the feature
feature.delete();
return noContent();
}
}
| true | true | public static Result find() {
if (!request().queryString().containsKey("query")) {
return ok();
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
return ok();
}
Integer limit = null;
if (request().queryString().get("limit") != null) {
limit = Integer.parseInt(request().queryString().get("limit")[0]);
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
Map<Long, Float> rankings = null;
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.eq("quarter", Integer.parseInt(term.substring(8)));
} else if (term.startsWith("assignedTo:")) {
where.eq("assignee_email", term.substring(11));
} else if (term.startsWith("text:")) {
rankings = new HashMap<>();
String tsquery = term.substring(5);
tsquery = tsquery.replaceAll("[\\|\\&\\!']", "-")
.replaceAll("[ \t\n\r]", "|");
SqlQuery searchQuery = Ebean.createSqlQuery("select id, ts_rank_cd(textsearch, query) rank from (select id, setweight(to_tsvector(coalesce((select string_agg(tag, ' ') from feature_tags where feature_id = id),'')), 'A') || setweight(to_tsvector(coalesce(title,'')), 'B') || setweight(to_tsvector(coalesce(description,'')), 'C') as textsearch from feature) t, to_tsquery(:tsquery) query where textsearch @@ query order by rank desc");
searchQuery.setParameter("tsquery", tsquery);
if (limit != null) {
searchQuery.setMaxRows(limit);
}
List<SqlRow> list = searchQuery.findList();
for (SqlRow row : list) {
rankings.put(row.getLong("id"), row.getFloat("rank"));
}
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
if (limit != null) {
tagQuery.setMaxRows(limit);
}
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
if (rankings != null) {
if (rankings.isEmpty()) {
return ok();
}
where.in("id", rankings.keySet());
}
// fixes N+1 query problem
where.join("creator");
where.join("lastModifiedBy");
if (limit != null) {
where.setMaxRows(limit);
}
List<Feature> list = where.findList();
if (rankings != null) {
for (Feature feature : list) {
feature.rank = rankings.get(feature.id);
}
}
JsonNode jsonNode = Json.toJson(dressFeatures(list));
return ok(jsonNode);
}
| public static Result find() {
if (!request().queryString().containsKey("query")) {
return ok();
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
return ok();
}
Integer limit = null;
if (request().queryString().get("limit") != null) {
limit = Integer.parseInt(request().queryString().get("limit")[0]);
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
Map<Long, Float> rankings = null;
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.eq("quarter", Integer.parseInt(term.substring(8)));
} else if (term.startsWith("assignedTo:")) {
String str = term.substring(11);
switch (str) {
case "null":
where.isNull("t0.assignee_email");
break;
case "not-null":
where.isNotNull("t0.assignee_email");
break;
default:
where.eq("t0.assignee_email", str);
break;
}
where.eq("assignee_email", term.substring(11));
} else if (term.startsWith("text:")) {
rankings = new HashMap<>();
String tsquery = term.substring(5);
tsquery = tsquery.replaceAll("[\\|\\&\\!']", "-")
.replaceAll("[ \t\n\r]", "|");
SqlQuery searchQuery = Ebean.createSqlQuery("select id, ts_rank_cd(textsearch, query) rank from (select id, setweight(to_tsvector(coalesce((select string_agg(tag, ' ') from feature_tags where feature_id = id),'')), 'A') || setweight(to_tsvector(coalesce(title,'')), 'B') || setweight(to_tsvector(coalesce(description,'')), 'C') as textsearch from feature) t, to_tsquery(:tsquery) query where textsearch @@ query order by rank desc");
searchQuery.setParameter("tsquery", tsquery);
if (limit != null) {
searchQuery.setMaxRows(limit);
}
List<SqlRow> list = searchQuery.findList();
for (SqlRow row : list) {
rankings.put(row.getLong("id"), row.getFloat("rank"));
}
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
if (limit != null) {
tagQuery.setMaxRows(limit);
}
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
if (rankings != null) {
if (rankings.isEmpty()) {
return ok();
}
where.in("id", rankings.keySet());
}
// fixes N+1 query problem
where.join("creator");
where.join("lastModifiedBy");
if (limit != null) {
where.setMaxRows(limit);
}
List<Feature> list = where.findList();
if (rankings != null) {
for (Feature feature : list) {
feature.rank = rankings.get(feature.id);
}
}
JsonNode jsonNode = Json.toJson(dressFeatures(list));
return ok(jsonNode);
}
|
diff --git a/plugins/org.eclipse.m2m.atl.drivers.uml24atl/src/org/eclipse/m2m/atl/drivers/uml24atl/ASMUMLModel.java b/plugins/org.eclipse.m2m.atl.drivers.uml24atl/src/org/eclipse/m2m/atl/drivers/uml24atl/ASMUMLModel.java
index e737cc2f..a3ea188c 100644
--- a/plugins/org.eclipse.m2m.atl.drivers.uml24atl/src/org/eclipse/m2m/atl/drivers/uml24atl/ASMUMLModel.java
+++ b/plugins/org.eclipse.m2m.atl.drivers.uml24atl/src/org/eclipse/m2m/atl/drivers/uml24atl/ASMUMLModel.java
@@ -1,645 +1,645 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA and C-S.
* 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:
* Frederic Jouault (INRIA) - initial API and implementation
* Freddy Allilaire (INRIA) - initial API and implementation
* Christophe Le Camus (C-S) - initial API and implementation
* Sebastien Gabel (C-S) - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.drivers.uml24atl;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.m2m.atl.ATLPlugin;
import org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel;
import org.eclipse.m2m.atl.engine.vm.ModelLoader;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMString;
/**
* The UML implementation of ASMModel.
*
* @author <a href="mailto:[email protected]">Frederic Jouault</a>
* @author <a href="mailto:[email protected]">Freddy Allilaire</a>
* @author <a href="mailto:[email protected]">Christophe Le Camus</a>
* @author <a href="mailto:[email protected]">Sebastien Gabel</a>
*/
public final class ASMUMLModel extends ASMEMFModel {
private static ResourceSet resourceSet;
private static ASMUMLModel mofmm;
// mof metamodel shall be unique for each model handler of a given type,
// but shall be redefined for a model handler that redefined a another model
// handler.
// use of static attributes is not advisable !
private Resource extent;
private Set referencedExtents = new HashSet();
private List delayedInvocations = new ArrayList();
/**
* Creates a new {@link ASMUMLModel}.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param isTarget
* true if the model is an output model
*/
private ASMUMLModel(String name, Resource extent, ASMUMLModel metamodel, boolean isTarget, ModelLoader ml) {
super(name, extent, metamodel, isTarget, ml);
this.extent = extent; // MOF UML2 PRO IN OUT
}
public static ASMModel getMOF() {
return ASMUMLModel.mofmm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#getASMModelElement(org.eclipse.emf.ecore.EObject)
*/
public ASMModelElement getASMModelElement(EObject object) {
ASMModelElement ret = null;
synchronized (modelElements) {
ret = (ASMModelElement)modelElements.get(object);
if (ret == null) {
ret = new ASMUMLModelElement(modelElements, this, object);
}
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#getElementsByType(org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement)
*/
public Set getElementsByType(ASMModelElement type) {
Set ret = new HashSet();
EClass t = (EClass)((ASMUMLModelElement)type).getObject();
addElementsOfType(ret, t, getExtent());
for (Iterator i = referencedExtents.iterator(); i.hasNext();) {
Resource res = (Resource)i.next();
addElementsOfType(ret, t, res);
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#newModelElement(org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement)
*/
public ASMModelElement newModelElement(ASMModelElement type) {
ASMModelElement ret = null;
EClass t = (EClass)((ASMUMLModelElement)type).getObject();
EObject eo = t.getEPackage().getEFactoryInstance().create(t);
ret = (ASMUMLModelElement)getASMModelElement(eo);
getExtent().getContents().add(eo);
return ret;
}
/**
* Simple Resource wrapping factory.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param extent
* the resource extent
* @param ml
* ModelLoader used to load the model if available, null otherwise.
* @return the loaded model
* @throws Exception
*/
public static ASMUMLModel loadASMUMLModel(String name, ASMUMLModel metamodel, Resource extent,
ModelLoader ml) throws Exception {
ASMUMLModel ret = null;
ret = new ASMUMLModel(name, extent, metamodel, false, ml);
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#dispose()
*/
public void dispose() {
if (extent != null) {
referencedExtents.clear();
referencedExtents = null;
for (Iterator unrs = unregister.iterator(); unrs.hasNext();) {
String nsURI = (String)unrs.next();
resourceSet.getPackageRegistry().remove(nsURI);
}
resourceSet.getResources().remove(extent);
if (unload) {
extent.unload();
}
extent = null;
modelElements.clear();
unregister.clear();
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#finalize()
*/
public void finalize() {
dispose();
try {
super.finalize();
} catch (Throwable e) {
ATLPlugin.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
/**
* Creates a new ASMEMFModel. Do not use this method for models that require a special registered factory
* (e.g. uml2).
*
* @param name
* The model name. Also used as EMF model URI.
* @param metamodel
* the metamodel
* @param ml
* the model loader
* @return the new ASMUMLModel
* @throws Exception
*/
public static ASMUMLModel newASMUMLModel(String name, ASMUMLModel metamodel, ModelLoader ml)
throws Exception {
return newASMUMLModel(name, name, metamodel, ml); // OUT
}
/**
* Creates a new ASMEMFModel.
*
* @param name
* The model name. Not used by EMF.
* @param uri
* The model URI. EMF uses this to determine the correct factory.
* @param metamodel
* the metamodel
* @param ml
* the model loader
* @return the new ASMUMLModel
* @throws Exception
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
*/
public static ASMUMLModel newASMUMLModel(String name, String uri, ASMUMLModel metamodel, ModelLoader ml)
throws Exception {
ASMUMLModel ret = null;
Resource extent = resourceSet.createResource(URI.createURI(uri));
ret = new ASMUMLModel(name, extent, metamodel, true, ml);
ret.unload = true;
return ret;
}
/**
* Loads an {@link ASMUMLModel}.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param url
* the model url (as String)
* @param ml
* the model loader
* @return the loaded model
* @throws Exception
*/
public static ASMUMLModel loadASMUMLModel(String name, ASMUMLModel metamodel, String url, ModelLoader ml)
throws Exception {
ASMUMLModel ret = null;
if (url.startsWith("uri:")) {
String uri = url.substring(4);
EPackage pack = resourceSet.getPackageRegistry().getEPackage(uri);
if (pack == null) {
ret = new ASMUMLModel(name, null, metamodel, false, ml);
ret.resolveURI = uri;
} else {
Resource extent = pack.eResource();
ret = new ASMUMLModel(name, extent, metamodel, false, ml);
ret.addAllReferencedExtents(extent);
}
} else {
ret = loadASMUMLModel(name, metamodel, URI.createURI(url), ml);
}
return ret;
}
/**
* Loads an {@link ASMUMLModel}.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param url
* the model url
* @param ml
* the model loader
* @return the loaded model
* @throws Exception
*/
public static ASMUMLModel loadASMUMLModel(String name, ASMUMLModel metamodel, URL url, ModelLoader ml)
throws Exception {
ASMUMLModel ret = null;
ret = loadASMUMLModel(name, metamodel, url.openStream(), ml);
return ret;
}
/**
* Loads an {@link ASMUMLModel}.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param uri
* the model uri
* @param ml
* the model loader
* @return the loaded model
* @throws Exception
*/
public static ASMUMLModel loadASMUMLModel(String name, ASMUMLModel metamodel, URI uri, ModelLoader ml)
throws Exception {
ASMUMLModel ret = null;
// PRO IN
try {
Resource extent = resourceSet.createResource(uri);
extent.load(Collections.EMPTY_MAP);
ret = new ASMUMLModel(name, extent, metamodel, true, ml);
ret.addAllReferencedExtents(extent);
ret.setIsTarget(false);
ret.unload = true;
} catch (Exception e) {
ATLPlugin.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
adaptMetamodel(ret, metamodel);
return ret;
}
/**
* Loads an {@link ASMUMLModel}.
*
* @param name
* the model name
* @param metamodel
* the metamodel
* @param in
* the model {@link InputStream}
* @param ml
* the model loader
* @return the loaded model
* @throws Exception
*/
public static ASMUMLModel loadASMUMLModel(String name, ASMUMLModel metamodel, InputStream in,
ModelLoader ml) throws Exception {
ASMUMLModel ret = newASMUMLModel(name, metamodel, ml);
try {
ret.getExtent().load(in, Collections.EMPTY_MAP);
ret.addAllReferencedExtents(ret.getExtent());
ret.unload = true;
} catch (Exception e) {
ATLPlugin.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
adaptMetamodel(ret, metamodel);
ret.setIsTarget(false);
return ret;
}
/**
* Adapts the model to its metamodel.
*
* @param model
* the model
* @param metamodel
* the metamodel
*/
private static void adaptMetamodel(ASMUMLModel model, ASMUMLModel metamodel) {
if (metamodel == mofmm) {
for (Iterator i = model.getElementsByType("EPackage").iterator(); i.hasNext();) {
ASMUMLModelElement ame = (ASMUMLModelElement)i.next();
EPackage p = (EPackage)ame.getObject();
String nsURI = p.getNsURI();
if (nsURI == null) {
nsURI = p.getName();
p.setNsURI(nsURI);
}
if (!resourceSet.getPackageRegistry().containsKey(nsURI)) {
model.unregister.add(nsURI);
}
resourceSet.getPackageRegistry().put(nsURI, p);
}
for (Iterator i = model.getElementsByType("EDataType").iterator(); i.hasNext();) {
ASMUMLModelElement ame = (ASMUMLModelElement)i.next();
String tname = ((ASMString)ame.get(null, "name")).getSymbol();
String icn = null;
if (tname.equals("Boolean")) {
icn = "boolean"; // "java.lang.Boolean";
} else if (tname.equals("Double")) {
icn = "java.lang.Double";
} else if (tname.equals("Float")) {
icn = "java.lang.Float";
} else if (tname.equals("Integer")) {
icn = "java.lang.Integer";
} else if (tname.equals("String")) {
icn = "java.lang.String";
}
if (icn != null) {
ame.set(null, "instanceClassName", new ASMString(icn));
}
}
}
/*
* reader.read(url.openStream(), url.toString(), ret.pack); ret.getAllAcquaintances();
*/
}
/*
* To be able to adapt return type (ASMUMLModel), we have to use jdk5 features (covariance)
*/
/**
* Creates the MOF metametamodel.
*
* @param ml
* the model loader
* @return the mof
*/
public static ASMEMFModel createMOF(ModelLoader ml) {
if (ASMUMLModel.mofmm == null) {
ASMUMLModel.mofmm = new ASMUMLModel("MOF", EcorePackage.eINSTANCE.eResource(), null, false, ml);
}
return ASMUMLModel.mofmm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#getExtent()
*/
public Resource getExtent() {
if ((extent == null) && (resolveURI != null)) {
EPackage pack = resourceSet.getPackageRegistry().getEPackage(resolveURI);
extent = pack.eResource();
addAllReferencedExtents();
}
return extent;
}
static {
init();
}
private static void init() {
Map etfm = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();
if (!etfm.containsKey("*")) {
etfm.put("*", new XMIResourceFactoryImpl());
}
resourceSet = new ResourceSetImpl();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#equals(java.lang.Object)
*/
public boolean equals(Object o) {
return (o instanceof ASMUMLModel) && (((ASMUMLModel)o).extent == extent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#hashCode()
*/
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#isCheckSameModel()
*/
public boolean isCheckSameModel() {
return checkSameModel;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#setCheckSameModel(boolean)
*/
public void setCheckSameModel(boolean checkSameModel) {
this.checkSameModel = checkSameModel;
}
/**
* Searches for and adds all Resource extents that are referenced from the main extent to
* referencedExtents.
*
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
*/
private void addAllReferencedExtents() {
Iterator contents = getExtent().getAllContents();
while (contents.hasNext()) {
Object o = contents.next();
if (o instanceof EClass) {
addReferencedExtentsFor((EClass)o, new HashSet());
}
}
referencedExtents.remove(getExtent());
}
/**
* Searches for and adds all Resource extents that are referenced from eClass to referencedExtents.
*
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
* @param eClass
* @param ignore
* Set of classes to ignore for searching.
*/
private void addReferencedExtentsFor(EClass eClass, Set ignore) {
if (ignore.contains(eClass)) {
return;
}
ignore.add(eClass);
Iterator eRefs = eClass.getEReferences().iterator();
while (eRefs.hasNext()) {
EReference eRef = (EReference)eRefs.next();
if (eRef.isContainment()) {
EClassifier eType = eRef.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
- ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eType.toString()
+ ATLPlugin.warning("Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
if (eType instanceof EClass) {
addReferencedExtentsFor((EClass)eType, ignore);
}
}
}
Iterator eAtts = eClass.getEAttributes().iterator();
while (eAtts.hasNext()) {
EAttribute eAtt = (EAttribute)eAtts.next();
EClassifier eType = eAtt.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
- ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eType.toString()
+ ATLPlugin.warning("Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
}
Iterator eSupers = eClass.getESuperTypes().iterator();
while (eSupers.hasNext()) {
EClass eSuper = (EClass)eSupers.next();
if (eSuper.eResource() != null) {
referencedExtents.add(eSuper.eResource());
addReferencedExtentsFor(eSuper, ignore);
} else {
- ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eSuper.toString()
+ ATLPlugin.warning("Resource for " + eSuper.toString()
+ " is null; cannot be referenced");
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel#getReferencedExtents()
*/
public Set getReferencedExtents() {
return referencedExtents;
}
/*
* // Unsupported Methods needed //
*/
/**
* Gets the last stereotype method in the delayed invocations list.
*
* @param opName
* the operation name
* @return the last stereotype method index
*/
public int getLastStereotypeMethod(String opName) {
int rang = 0;
for (int i = 0; i < delayedInvocations.size(); i++) {
Invocation invoc = (Invocation)(delayedInvocations.get(rang));
if (invoc.getOpName().equals(opName)) {
rang = i;
}
}
return rang;
}
/**
* Delays an invocation.
*
* @param invocation
* the operation invocation to delay
*/
public void addDelayedInvocation(Invocation invocation) {
// Guarantee the applied profiles operations are the first applied
if (invocation.getOpName().equals("applyProfile")) {
delayedInvocations.add(0, invocation);
} else {
if (invocation.getOpName().equals("applyStereotype")
|| invocation.getOpName().equals("applyAllStereotypes")
|| invocation.getOpName().equals("applyAllRequiredStereotypes")) {
// Guarantee the applied stereotypes operations are applied
// before setValue and after applyProfile
int lastApplyProfile = getLastStereotypeMethod("applyProfile");
if (lastApplyProfile < delayedInvocations.size() - 1) {
delayedInvocations.add(lastApplyProfile + 1, invocation);
} else {
delayedInvocations.add(invocation);
}
} else {
// SetValue operation follow this way
delayedInvocations.add(invocation);
}
}
}
/**
* Applies all delayed operation invocations.
*/
public void applyDelayedInvocations() {
for (Iterator i = delayedInvocations.iterator(); i.hasNext();) {
Invocation invocation = (Invocation)i.next();
invocation.getSelf().realInvoke(invocation.getFrame(), invocation.getOpName(),
invocation.getArguments());
}
}
}
| false | true | private void addReferencedExtentsFor(EClass eClass, Set ignore) {
if (ignore.contains(eClass)) {
return;
}
ignore.add(eClass);
Iterator eRefs = eClass.getEReferences().iterator();
while (eRefs.hasNext()) {
EReference eRef = (EReference)eRefs.next();
if (eRef.isContainment()) {
EClassifier eType = eRef.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
if (eType instanceof EClass) {
addReferencedExtentsFor((EClass)eType, ignore);
}
}
}
Iterator eAtts = eClass.getEAttributes().iterator();
while (eAtts.hasNext()) {
EAttribute eAtt = (EAttribute)eAtts.next();
EClassifier eType = eAtt.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
}
Iterator eSupers = eClass.getESuperTypes().iterator();
while (eSupers.hasNext()) {
EClass eSuper = (EClass)eSupers.next();
if (eSuper.eResource() != null) {
referencedExtents.add(eSuper.eResource());
addReferencedExtentsFor(eSuper, ignore);
} else {
ATLPlugin.log(Level.SEVERE, "WARNING: Resource for " + eSuper.toString()
+ " is null; cannot be referenced");
}
}
}
| private void addReferencedExtentsFor(EClass eClass, Set ignore) {
if (ignore.contains(eClass)) {
return;
}
ignore.add(eClass);
Iterator eRefs = eClass.getEReferences().iterator();
while (eRefs.hasNext()) {
EReference eRef = (EReference)eRefs.next();
if (eRef.isContainment()) {
EClassifier eType = eRef.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
ATLPlugin.warning("Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
if (eType instanceof EClass) {
addReferencedExtentsFor((EClass)eType, ignore);
}
}
}
Iterator eAtts = eClass.getEAttributes().iterator();
while (eAtts.hasNext()) {
EAttribute eAtt = (EAttribute)eAtts.next();
EClassifier eType = eAtt.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
ATLPlugin.warning("Resource for " + eType.toString()
+ " is null; cannot be referenced");
}
}
Iterator eSupers = eClass.getESuperTypes().iterator();
while (eSupers.hasNext()) {
EClass eSuper = (EClass)eSupers.next();
if (eSuper.eResource() != null) {
referencedExtents.add(eSuper.eResource());
addReferencedExtentsFor(eSuper, ignore);
} else {
ATLPlugin.warning("Resource for " + eSuper.toString()
+ " is null; cannot be referenced");
}
}
}
|
diff --git a/shell/impl/src/main/java/org/jboss/forge/addon/shell/aesh/completion/ForgeCompletion.java b/shell/impl/src/main/java/org/jboss/forge/addon/shell/aesh/completion/ForgeCompletion.java
index 0fb00690f..7ccac8c8b 100644
--- a/shell/impl/src/main/java/org/jboss/forge/addon/shell/aesh/completion/ForgeCompletion.java
+++ b/shell/impl/src/main/java/org/jboss/forge/addon/shell/aesh/completion/ForgeCompletion.java
@@ -1,129 +1,129 @@
/**
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.shell.aesh.completion;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.jboss.aesh.cl.ParsedCompleteObject;
import org.jboss.aesh.cl.internal.ParameterInt;
import org.jboss.aesh.complete.CompleteOperation;
import org.jboss.aesh.complete.Completion;
import org.jboss.forge.addon.shell.ShellImpl;
import org.jboss.forge.addon.shell.aesh.ShellCommand;
import org.jboss.forge.addon.shell.ui.ShellContext;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* @author <a href="[email protected]">George Gastaldi</a>
*/
public class ForgeCompletion implements Completion
{
private static final Logger logger = Logger.getLogger(ForgeCompletion.class.getName());
/**
* the name of the arguments {@link InputComponent} (if exists)
*/
private static final String ARGUMENTS_INPUT_NAME = "arguments";
private ShellImpl shell;
public ForgeCompletion(ShellImpl shellImpl)
{
this.shell = shellImpl;
}
@Override
public void complete(CompleteOperation completeOperation)
{
String line = completeOperation.getBuffer();
ShellContext shellContext = shell.newShellContext();
final ShellCommand cmd = shell.findCommand(shellContext, line);
if (cmd == null)
{
Collection<ShellCommand> commands = shell.findMatchingCommands(shellContext, line);
for (ShellCommand command : commands)
{
completeOperation.addCompletionCandidate(command.getName());
}
}
else
{
try
{
// We are dealing with one-level commands only.
// Eg. new-project-type --named ... instead of new-project-type setup --named ...
ParameterInt param = cmd.getParameter();
ParsedCompleteObject completeObject = cmd.parseCompleteObject(line);
if (completeObject.doDisplayOptions())
{
// we have a partial/full name
if (completeObject.getName() != null && !completeObject.getName().isEmpty())
{
List<String> possibleOptions = param.findPossibleLongNamesWitdDash(completeObject.getName());
completeOperation.addCompletionCandidates(possibleOptions);
}
else
{
List<String> optionNames = param.getOptionLongNamesWithDash();
removeExistingOptions(line, optionNames);
// All the not-informed parameters
completeOperation.addCompletionCandidates(optionNames);
}
+ if (completeOperation.getCompletionCandidates().size() == 1)
+ {
+ completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset());
+ }
}
else
{
final InputComponent<?, Object> input;
if (completeObject.isOption())
{
// try to complete an option value. Eg: "--xxx"
input = cmd.getInputs().get(completeObject.getName());
}
// try to complete a argument value Eg: ls . (. is the argument)
else if (completeObject.isArgument())
{
input = cmd.getInputs().get(ARGUMENTS_INPUT_NAME); // default for arguments
}
else
{
input = null;
}
if (input != null)
{
CompletionStrategy completionObj = CompletionStrategyFactory.getCompletionFor(input);
completionObj.complete(completeOperation, input, shellContext, completeObject.getValue(),
shell.getConverterFactory());
}
}
- if (completeOperation.getCompletionCandidates().size() == 1)
- {
- completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset());
- }
}
catch (Exception e)
{
logger.warning(e.getMessage());
return;
}
}
}
private void removeExistingOptions(String commandLine, Iterable<String> availableOptions)
{
Iterator<String> it = availableOptions.iterator();
while (it.hasNext())
{
if (commandLine.contains(it.next()))
{
it.remove();
}
}
}
}
| false | true | public void complete(CompleteOperation completeOperation)
{
String line = completeOperation.getBuffer();
ShellContext shellContext = shell.newShellContext();
final ShellCommand cmd = shell.findCommand(shellContext, line);
if (cmd == null)
{
Collection<ShellCommand> commands = shell.findMatchingCommands(shellContext, line);
for (ShellCommand command : commands)
{
completeOperation.addCompletionCandidate(command.getName());
}
}
else
{
try
{
// We are dealing with one-level commands only.
// Eg. new-project-type --named ... instead of new-project-type setup --named ...
ParameterInt param = cmd.getParameter();
ParsedCompleteObject completeObject = cmd.parseCompleteObject(line);
if (completeObject.doDisplayOptions())
{
// we have a partial/full name
if (completeObject.getName() != null && !completeObject.getName().isEmpty())
{
List<String> possibleOptions = param.findPossibleLongNamesWitdDash(completeObject.getName());
completeOperation.addCompletionCandidates(possibleOptions);
}
else
{
List<String> optionNames = param.getOptionLongNamesWithDash();
removeExistingOptions(line, optionNames);
// All the not-informed parameters
completeOperation.addCompletionCandidates(optionNames);
}
}
else
{
final InputComponent<?, Object> input;
if (completeObject.isOption())
{
// try to complete an option value. Eg: "--xxx"
input = cmd.getInputs().get(completeObject.getName());
}
// try to complete a argument value Eg: ls . (. is the argument)
else if (completeObject.isArgument())
{
input = cmd.getInputs().get(ARGUMENTS_INPUT_NAME); // default for arguments
}
else
{
input = null;
}
if (input != null)
{
CompletionStrategy completionObj = CompletionStrategyFactory.getCompletionFor(input);
completionObj.complete(completeOperation, input, shellContext, completeObject.getValue(),
shell.getConverterFactory());
}
}
if (completeOperation.getCompletionCandidates().size() == 1)
{
completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset());
}
}
catch (Exception e)
{
logger.warning(e.getMessage());
return;
}
}
}
| public void complete(CompleteOperation completeOperation)
{
String line = completeOperation.getBuffer();
ShellContext shellContext = shell.newShellContext();
final ShellCommand cmd = shell.findCommand(shellContext, line);
if (cmd == null)
{
Collection<ShellCommand> commands = shell.findMatchingCommands(shellContext, line);
for (ShellCommand command : commands)
{
completeOperation.addCompletionCandidate(command.getName());
}
}
else
{
try
{
// We are dealing with one-level commands only.
// Eg. new-project-type --named ... instead of new-project-type setup --named ...
ParameterInt param = cmd.getParameter();
ParsedCompleteObject completeObject = cmd.parseCompleteObject(line);
if (completeObject.doDisplayOptions())
{
// we have a partial/full name
if (completeObject.getName() != null && !completeObject.getName().isEmpty())
{
List<String> possibleOptions = param.findPossibleLongNamesWitdDash(completeObject.getName());
completeOperation.addCompletionCandidates(possibleOptions);
}
else
{
List<String> optionNames = param.getOptionLongNamesWithDash();
removeExistingOptions(line, optionNames);
// All the not-informed parameters
completeOperation.addCompletionCandidates(optionNames);
}
if (completeOperation.getCompletionCandidates().size() == 1)
{
completeOperation.setOffset(completeOperation.getCursor() - completeObject.getOffset());
}
}
else
{
final InputComponent<?, Object> input;
if (completeObject.isOption())
{
// try to complete an option value. Eg: "--xxx"
input = cmd.getInputs().get(completeObject.getName());
}
// try to complete a argument value Eg: ls . (. is the argument)
else if (completeObject.isArgument())
{
input = cmd.getInputs().get(ARGUMENTS_INPUT_NAME); // default for arguments
}
else
{
input = null;
}
if (input != null)
{
CompletionStrategy completionObj = CompletionStrategyFactory.getCompletionFor(input);
completionObj.complete(completeOperation, input, shellContext, completeObject.getValue(),
shell.getConverterFactory());
}
}
}
catch (Exception e)
{
logger.warning(e.getMessage());
return;
}
}
}
|
diff --git a/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java b/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java
index 32420e91..27824f58 100644
--- a/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java
+++ b/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java
@@ -1,130 +1,131 @@
/**
* Copyright (C) 2012
* by 52North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.importer.feeder.model;
/**
* @author <a href="mailto:[email protected]">Eike Hinderk Jürrens</a>
*/
public class Timestamp {
private short year = Short.MIN_VALUE;
private byte month = Byte.MIN_VALUE;
private byte day = Byte.MIN_VALUE;
private byte hour = Byte.MIN_VALUE;
private byte minute = Byte.MIN_VALUE;
private byte seconds = Byte.MIN_VALUE;
private byte timezone = Byte.MIN_VALUE;
@Override
public String toString() {
StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm
if (year != Short.MIN_VALUE) {
ts.append(year);
if (month != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (month != Byte.MIN_VALUE) {
ts.append(month<10?"0"+month:month);
if (day != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (day != Byte.MIN_VALUE) {
ts.append(day<10?"0"+day:day);
}
if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE )
&& (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append("T");
}
if (hour != Byte.MIN_VALUE) {
ts.append(hour<10?"0"+hour:hour);
if (minute != Byte.MIN_VALUE) {
ts.append(":");
}
}
if (minute != Byte.MIN_VALUE) {
- ts.append(minute<10?"0"+minute:minute);
- if (seconds != Byte.MIN_VALUE) {
- ts.append(":");
- }
+ ts.append( (minute<10?"0"+minute:minute)+":");
+ } else if (hour != Byte.MIN_VALUE) {
+ ts.append("00:");
}
- if (seconds != Byte.MIN_VALUE) {
+ if (seconds != Byte.MIN_VALUE ) {
ts.append(seconds<10?"0"+seconds:seconds);
+ } else if (minute != Byte.MIN_VALUE && hour != Byte.MIN_VALUE) {
+ ts.append("00");
}
if (timezone != Byte.MIN_VALUE &&
(hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append(convertTimeZone(timezone));
}
return ts.toString();
}
private String convertTimeZone(int timeZone) {
if (timeZone >= 0) {
if (timeZone >= 10) {
return "+" + timeZone + ":00";
} else {
return "+0" + timeZone + ":00";
}
} else {
if (timeZone <= -10) {
return timeZone + ":00";
} else {
return "-0" + Math.abs(timeZone) + ":00";
}
}
}
public void setYear(short year) {
this.year = year;
}
public void setMonth(byte month) {
this.month = month;
}
public void setDay(byte day) {
this.day = day;
}
public void setHour(byte hour) {
this.hour = hour;
}
public void setMinute(byte minute) {
this.minute = minute;
}
public void setSeconds(byte seconds) {
this.seconds = seconds;
}
public void setTimezone(byte timezone) {
this.timezone = timezone;
}
}
| false | true | public String toString() {
StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm
if (year != Short.MIN_VALUE) {
ts.append(year);
if (month != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (month != Byte.MIN_VALUE) {
ts.append(month<10?"0"+month:month);
if (day != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (day != Byte.MIN_VALUE) {
ts.append(day<10?"0"+day:day);
}
if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE )
&& (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append("T");
}
if (hour != Byte.MIN_VALUE) {
ts.append(hour<10?"0"+hour:hour);
if (minute != Byte.MIN_VALUE) {
ts.append(":");
}
}
if (minute != Byte.MIN_VALUE) {
ts.append(minute<10?"0"+minute:minute);
if (seconds != Byte.MIN_VALUE) {
ts.append(":");
}
}
if (seconds != Byte.MIN_VALUE) {
ts.append(seconds<10?"0"+seconds:seconds);
}
if (timezone != Byte.MIN_VALUE &&
(hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append(convertTimeZone(timezone));
}
return ts.toString();
}
| public String toString() {
StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm
if (year != Short.MIN_VALUE) {
ts.append(year);
if (month != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (month != Byte.MIN_VALUE) {
ts.append(month<10?"0"+month:month);
if (day != Byte.MIN_VALUE) {
ts.append("-");
}
}
if (day != Byte.MIN_VALUE) {
ts.append(day<10?"0"+day:day);
}
if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE )
&& (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append("T");
}
if (hour != Byte.MIN_VALUE) {
ts.append(hour<10?"0"+hour:hour);
if (minute != Byte.MIN_VALUE) {
ts.append(":");
}
}
if (minute != Byte.MIN_VALUE) {
ts.append( (minute<10?"0"+minute:minute)+":");
} else if (hour != Byte.MIN_VALUE) {
ts.append("00:");
}
if (seconds != Byte.MIN_VALUE ) {
ts.append(seconds<10?"0"+seconds:seconds);
} else if (minute != Byte.MIN_VALUE && hour != Byte.MIN_VALUE) {
ts.append("00");
}
if (timezone != Byte.MIN_VALUE &&
(hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) {
ts.append(convertTimeZone(timezone));
}
return ts.toString();
}
|
diff --git a/test/models/support/FinderTemplateTest.java b/test/models/support/FinderTemplateTest.java
index 6c693af2..38417a9d 100644
--- a/test/models/support/FinderTemplateTest.java
+++ b/test/models/support/FinderTemplateTest.java
@@ -1,42 +1,42 @@
package models.support;
import models.Milestone;
import models.ModelTest;
import models.enumeration.Direction;
import models.enumeration.Matching;
import org.junit.Test;
import play.db.ebean.Model;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
public class FinderTemplateTest extends ModelTest {
private static Model.Finder<Long, Milestone> find = new Model.Finder<Long, Milestone>(
Long.class, Milestone.class);
@Test
public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.LT);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
- assertThat(p2MilestoneList.get(0).getId()).isEqualTo(5);
+ assertThat(p2MilestoneList.get(0).id).isEqualTo(5);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
- assertThat(p1MilestoneList.get(0).getId()).isEqualTo(1);
+ assertThat(p1MilestoneList.get(0).id).isEqualTo(1);
}
}
| false | true | public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.LT);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p2MilestoneList.get(0).getId()).isEqualTo(5);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p1MilestoneList.get(0).getId()).isEqualTo(1);
}
| public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.LT);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p2MilestoneList.get(0).id).isEqualTo(5);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p1MilestoneList.get(0).id).isEqualTo(1);
}
|
diff --git a/src/java/com/idega/presentation/ui/TextInput.java b/src/java/com/idega/presentation/ui/TextInput.java
index 94548c767..519f65196 100755
--- a/src/java/com/idega/presentation/ui/TextInput.java
+++ b/src/java/com/idega/presentation/ui/TextInput.java
@@ -1,285 +1,285 @@
//idega 2000 - Tryggvi Larusson
/*
*Copyright 2000 idega.is All Rights Reserved.
*/
package com.idega.presentation.ui;
import java.io.*;
import java.util.*;
import com.idega.presentation.*;
/**
*@author <a href="mailto:[email protected]">Tryggvi Larusson</a>
*@version 1.2
*/
public class TextInput extends InterfaceObject{
private String inputType = "text";
private Script script;
private boolean isSetAsIntegers;
private boolean isSetAsFloat;
private boolean isSetAsAlphabetical;
private boolean isSetAsEmail;
private boolean isSetAsNotEmpty;
private boolean isSetAsIcelandicSSNumber;
private boolean isSetAsCreditCardNumber;
private String integersErrorMessage;
private String floatErrorMessage;
private String alphabetErrorMessage;
private String emailErrorMessage;
private String notEmptyErrorMessage;
private String icelandicSSNumberErrorMessage;
private String notCreditCardErrorMessage;
private static final String untitled="untitled";
public TextInput(){
this(untitled);
}
public TextInput(String name){
super();
setName(name);
}
public TextInput(String name,String content){
super();
setName(name);
setContent(content);
isSetAsIntegers=false;
isSetAsFloat=false;
isSetAsAlphabetical=false;
isSetAsEmail=false;
isSetAsNotEmpty=false;
isSetAsIcelandicSSNumber=false;
}
public void setAsPasswordInput(boolean asPasswordInput) {
if ( asPasswordInput )
inputType = "password";
else
inputType = "text";
}
public void setLength(int length){
setSize(length);
}
public void setSize(int size){
setAttribute("size",Integer.toString(size));
}
public void setMaxlength(int maxlength){
setAttribute("maxlength",Integer.toString(maxlength));
}
private void setScript(Script script){
this.script = script;
setAssociatedScript(script);
}
private Script getScript(){
if (getAssociatedScript() == null){
setScript(new Script());
}
else
{
script = getAssociatedScript();
}
return script;
}
private void setCheckSubmit(){
if ( getScript().getFunction("checkSubmit") == null){
getScript().addFunction("checkSubmit","function checkSubmit(inputs){\n\n}");
}
}
public void setAsNotEmpty(){
this.setAsNotEmpty("Please fill in the box "+this.getName());
}
public void setAsNotEmpty(String errorMessage){
isSetAsNotEmpty=true;
notEmptyErrorMessage=errorMessage;
}
public void setAsCredidCardNumber(){
this.setAsCredidCardNumber("Please enter a valid creditcard number in "+this.getName());
}
public void setAsCredidCardNumber(String errorMessage){
isSetAsCreditCardNumber=true;
notCreditCardErrorMessage=errorMessage;
}
public void setAsEmail(String errorMessage){
isSetAsEmail=true;
emailErrorMessage=errorMessage;
}
public void setAsEmail(){
this.setAsEmail("This is not an email");
}
public void setAsIntegers(){
this.setAsIntegers("Please use only numbers in "+this.getName());
}
public void setAsIntegers(String errorMessage){
isSetAsIntegers=true;
integersErrorMessage=errorMessage;
}
public void setAsFloat(){
this.setAsFloat("Please use only numbers in "+this.getName());
}
public void setAsFloat(String errorMessage){
isSetAsFloat=true;
floatErrorMessage=errorMessage;
}
public void setAsIcelandicSSNumber(){
this.setAsFloat("Please only a Icelandic social security number in "+this.getName());
}
//Checks if it is a valid "kennitala" (social security number)
public void setAsIcelandicSSNumber(String errorMessage){
isSetAsIntegers=true;
isSetAsIcelandicSSNumber=true;
icelandicSSNumberErrorMessage=errorMessage;
}
public void setAsAlphabetictext(){
this.setAsAlphabeticText("Please use only alpabetical characters in "+this.getName());
}
public void setAsAlphabeticText(String errorMessage){
isSetAsAlphabetical=true;
alphabetErrorMessage=errorMessage;
}
public void setStyle(String style) {
setAttribute("class",style);
}
public String getValue(){
if (super.getValue() == null){
return "";
}
else{
return super.getValue();
}
}
public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfEmpty (inputs."+getName()+",'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfEmpty (findObj('"+getName()+"'),'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (inputs."+getName()+",'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (inputs."+getName()+",'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n if ((inputbox.value.charAt(8) == 11 - (sum % 11)) && ((inputbox.value.charAt(9) == 0) || (inputbox.value.charAt(9) == 8) || (inputbox.value.charAt(9) == 9))){ \n return true; \n }\n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (inputs."+getName()+",'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (findObj('"+getName()+"'),'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (inputs."+getName()+",'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (findObj('"+getName()+"'),'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
- getScript().addToFunction("checkSubmit","if (warnIfNotEmail (inputs."+getName()+") == false ){\nreturn false;\n}\n");
+ getScript().addToFunction("checkSubmit","if (warnIfNotEmail (findObj('"+getName()+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
public void print(IWContext iwc)throws IOException{
//if ( doPrint(iwc) ){
if (getLanguage().equals("HTML")){
if (keepStatus){
if(this.getRequest().getParameter(this.getName()) != null){
setContent(getRequest().getParameter(getName()));
}
}
//if (getInterfaceStyle().equals("default"))
println("<input type=\""+inputType+"\" name=\""+getName()+"\" "+getAttributeString()+" >");
//println("</input>");
// }
}
else if (getLanguage().equals("WML")){
println("<input type=\""+inputType+"\" name=\""+getName()+"\" "+getAttributeString()+" />");
}
//}
}
public synchronized Object clone() {
TextInput obj = null;
try {
obj = (TextInput)super.clone();
if(this.script != null){
obj.script = (Script)this.script.clone();
}
obj.isSetAsIntegers = this.isSetAsIntegers;
obj.isSetAsFloat = this.isSetAsFloat;
obj.isSetAsAlphabetical = this.isSetAsAlphabetical;
obj.isSetAsEmail = this.isSetAsEmail;
obj.isSetAsNotEmpty = this.isSetAsNotEmpty;
obj.integersErrorMessage = this.integersErrorMessage;
obj.floatErrorMessage = this.floatErrorMessage;
obj.alphabetErrorMessage = this.alphabetErrorMessage;
obj.emailErrorMessage = this.emailErrorMessage;
obj.notEmptyErrorMessage = this.notEmptyErrorMessage;
}
catch(Exception ex) {
ex.printStackTrace(System.err);
}
return obj;
}
}
| false | true | public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfEmpty (inputs."+getName()+",'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (inputs."+getName()+",'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (inputs."+getName()+",'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n if ((inputbox.value.charAt(8) == 11 - (sum % 11)) && ((inputbox.value.charAt(9) == 0) || (inputbox.value.charAt(9) == 8) || (inputbox.value.charAt(9) == 9))){ \n return true; \n }\n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (inputs."+getName()+",'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (inputs."+getName()+",'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotEmail (inputs."+getName()+") == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
| public void _main(IWContext iwc)throws Exception{
if (getParentForm() != null){
if (isSetAsNotEmpty){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfEmpty (findObj('"+getName()+"'),'"+notEmptyErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfEmpty","function warnIfEmpty (inputbox,warnMsg) {\n\n if ( inputbox.value == '' ) { \n alert ( warnMsg );\n return false;\n }\n else{\n return true;\n}\n\n}");
}
if (isSetAsIntegers){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIntegers (findObj('"+getName()+"'),'"+integersErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIntegers","function warnIfNotIntegers (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if (inputbox.value.charAt(i) < '0'){ \n alert ( warnMsg );\n return false; \n } \n if(inputbox.value.charAt(i) > '9'){ \n alert ( warnMsg );\n return false;\n } \n } \n return true;\n\n}");
}
if(isSetAsIcelandicSSNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotIcelandicSSNumber (findObj('"+getName()+"'),'"+icelandicSSNumberErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotIcelandicSSNumber","function warnIfNotIcelandicSSNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 10){ \n sum = inputbox.value.charAt(0)*3 + inputbox.value.charAt(1)*2 + inputbox.value.charAt(2)*7 + inputbox.value.charAt(3)*6 + inputbox.value.charAt(4)*5 + inputbox.value.charAt(5)*4 + inputbox.value.charAt(6)*3 + inputbox.value.charAt(7)*2; \n if ((inputbox.value.charAt(8) == 11 - (sum % 11)) && ((inputbox.value.charAt(9) == 0) || (inputbox.value.charAt(9) == 8) || (inputbox.value.charAt(9) == 9))){ \n return true; \n }\n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
}
if (isSetAsCreditCardNumber){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotCreditCardNumber (findObj('"+getName()+"'),'"+notCreditCardErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotCreditCardNumber","function warnIfNotCreditCardNumber (inputbox,warnMsg) {\n \n if (inputbox.value.length == 16){ \n return true; \n } \n else if (inputbox.value.length == 0){\n return true; \n } \n alert ( warnMsg );\n return false;\n \n }");
//not fully implemented such as maybe a checksum check could be added??
}
else if(isSetAsFloat){
getParentForm().setOnSubmit("return checkSubmit(this)");
//Not implemented yet
}
else if(isSetAsAlphabetical){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotAlphabetical (findObj('"+getName()+"'),'"+alphabetErrorMessage+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotAlphabetical","function warnIfNotAlphabetical (inputbox,warnMsg) {\n \n for(i=0; i < inputbox.value.length; i++) { \n if ((inputbox.value.charAt(i) > '0') && (inputbox.value.charAt(i) < '9')){ \n alert ( warnMsg );\n return false; \n } \n } \n return true;\n\n}");
}
else if(isSetAsEmail){
getParentForm().setOnSubmit("return checkSubmit(this)");
setCheckSubmit();
getScript().addToFunction("checkSubmit","if (warnIfNotEmail (findObj('"+getName()+"') == false ){\nreturn false;\n}\n");
getScript().addFunction("warnIfNotEmail","function warnIfNotEmail (inputbox) { \n\n var emailVal = inputbox.value; \n\n var atI = emailVal.indexOf (\"@\"); \n\n var dotI = emailVal.indexOf (\".\"); \n\n var warnMsg = \""+emailErrorMessage+"\\n\";\n\n if ( atI && dotI ){\n return true;\n }\n else{\n alert(warnMsg);\n return false;\n }\n}");
//Not finished yet
}
}
}
|
diff --git a/SolarPanelApp/src/com/example/calendar/BasicCalendar.java b/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
index 9ee01e8..2056798 100644
--- a/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
+++ b/SolarPanelApp/src/com/example/calendar/BasicCalendar.java
@@ -1,56 +1,56 @@
package com.example.calendar;
import java.util.Collection;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
import com.example.solarpanelmanager.api.responses.Event;
public class BasicCalendar {
private Map<String, Event> calendar = new TreeMap<String, Event>();
private static final long DAY_MILLIS = 24 * 60 * 60 * 1000;
public BasicCalendar(Collection<Event> events) {
for (Event e : events)
addEvent(e);
}
public boolean addEvent(Event event) {
for (Event e : calendar.values()) {
if (isOverlap(event, e))
return false;
}
calendar.put(eventToKey(event), event);
return true;
}
public void removeEvent(Event event) {
calendar.remove(eventToKey(event));
}
public Map<String, Event> getCalendar() {
return calendar;
}
private static String eventToKey(Event e) {
Calendar day = Calendar.getInstance();
day.setTimeInMillis(e.getFirstTime());
return day.get(Calendar.HOUR) + ":" + day.get(Calendar.MINUTE);
}
private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
- long newStart = ((newDay.get(Calendar.HOUR) * 60 + newDay.get(Calendar.MINUTE)) * 60 * 1000) % DAY_MILLIS;
+ long newStart = (newDay.get(Calendar.HOUR) * 60 * 60 * 1000 + newDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
- long oldStart = ((oldDay.get(Calendar.HOUR) * 60 + oldDay.get(oldDay.get(Calendar.MINUTE)) * 60 * 1000)) % DAY_MILLIS;
+ long oldStart = (oldDay.get(Calendar.HOUR) * 60 * 60 * 1000 + oldDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
}
| false | true | private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
long newStart = ((newDay.get(Calendar.HOUR) * 60 + newDay.get(Calendar.MINUTE)) * 60 * 1000) % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
long oldStart = ((oldDay.get(Calendar.HOUR) * 60 + oldDay.get(oldDay.get(Calendar.MINUTE)) * 60 * 1000)) % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
| private static boolean isOverlap(Event e1, Event e2) {
Calendar newDay = Calendar.getInstance();
newDay.setTimeInMillis(e1.getFirstTime());
long newStart = (newDay.get(Calendar.HOUR) * 60 * 60 * 1000 + newDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long newEnd = (newStart + e1.getDuration()) % DAY_MILLIS;
Calendar oldDay = Calendar.getInstance();
oldDay.setTimeInMillis(e2.getFirstTime());
long oldStart = (oldDay.get(Calendar.HOUR) * 60 * 60 * 1000 + oldDay.get(Calendar.MINUTE) * 60 * 1000) % DAY_MILLIS;
long oldEnd = (oldStart + e2.getDuration()) % DAY_MILLIS;
return (newStart >= oldStart && newStart < oldEnd) || (newEnd <= oldEnd && newEnd > oldStart);
}
|
diff --git a/libraries/javalib/external/classpath/gnu/java/util/regex/RETokenChar.java b/libraries/javalib/external/classpath/gnu/java/util/regex/RETokenChar.java
index b70e6b1d8..42dcd9326 100644
--- a/libraries/javalib/external/classpath/gnu/java/util/regex/RETokenChar.java
+++ b/libraries/javalib/external/classpath/gnu/java/util/regex/RETokenChar.java
@@ -1,134 +1,135 @@
/* gnu/regexp/RETokenChar.java
Copyright (C) 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 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.util.regex;
final class RETokenChar extends REToken {
private char[] ch;
private boolean insens;
RETokenChar(int subIndex, char c, boolean ins) {
super(subIndex);
insens = ins;
ch = new char [1];
ch[0] = c;
}
int getMinimumLength() {
return ch.length;
}
int getMaximumLength() {
return ch.length;
}
REMatch matchThis(CharIndexed input, REMatch mymatch) {
if (matchOneString(input, mymatch.index)) {
mymatch.index += matchedLength;
return mymatch;
}
// java.util.regex.Matcher#hitEnd() requires that the length of
// partial match be counted.
mymatch.index += matchedLength;
input.setHitEnd(mymatch);
return null;
}
private int matchedLength;
private boolean matchOneString(CharIndexed input, int index) {
matchedLength = 0;
int z = ch.length;
char c;
for (int i=0; i<z; i++) {
c = input.charAt(index+i);
if (! charEquals(c, ch[i])) {
return false;
}
++matchedLength;
}
return true;
}
private boolean charEquals(char c1, char c2) {
if (c1 == c2) return true;
if (! insens) return false;
if (toLowerCase(c1, unicodeAware) == c2) return true;
if (toUpperCase(c1, unicodeAware) == c2) return true;
return false;
}
boolean returnsFixedLengthMatches() { return true; }
int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
int index = mymatch.index;
int numRepeats = 0;
int z = ch.length;
while (true) {
if (numRepeats >= max) break;
if (matchOneString(input, index)) {
index += z;
numRepeats++;
}
else break;
}
return numRepeats;
}
// Overrides REToken.chain() to optimize for strings
boolean chain(REToken next) {
if (next instanceof RETokenChar && ((RETokenChar)next).insens == insens) {
RETokenChar cnext = (RETokenChar) next;
- // assume for now that next can only be one character
int newsize = ch.length + cnext.ch.length;
char[] chTemp = new char [newsize];
System.arraycopy(ch,0,chTemp,0,ch.length);
System.arraycopy(cnext.ch,0,chTemp,ch.length,cnext.ch.length);
ch = chTemp;
- return false;
+ if (cnext.next == null)
+ return false;
+ return chain(cnext.next);
} else return super.chain(next);
}
void dump(StringBuffer os) {
os.append(ch);
}
}
| false | true | boolean chain(REToken next) {
if (next instanceof RETokenChar && ((RETokenChar)next).insens == insens) {
RETokenChar cnext = (RETokenChar) next;
// assume for now that next can only be one character
int newsize = ch.length + cnext.ch.length;
char[] chTemp = new char [newsize];
System.arraycopy(ch,0,chTemp,0,ch.length);
System.arraycopy(cnext.ch,0,chTemp,ch.length,cnext.ch.length);
ch = chTemp;
return false;
} else return super.chain(next);
}
| boolean chain(REToken next) {
if (next instanceof RETokenChar && ((RETokenChar)next).insens == insens) {
RETokenChar cnext = (RETokenChar) next;
int newsize = ch.length + cnext.ch.length;
char[] chTemp = new char [newsize];
System.arraycopy(ch,0,chTemp,0,ch.length);
System.arraycopy(cnext.ch,0,chTemp,ch.length,cnext.ch.length);
ch = chTemp;
if (cnext.next == null)
return false;
return chain(cnext.next);
} else return super.chain(next);
}
|
diff --git a/src/data/GameData.java b/src/data/GameData.java
index 4cc778b..370969e 100644
--- a/src/data/GameData.java
+++ b/src/data/GameData.java
@@ -1,1012 +1,1017 @@
package data;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Random;
import java.util.EnumSet;
import javax.swing.SwingUtilities;
import json.simple.JSONArray;
import json.simple.JSONObject;
import json.simple.parser.ParseException;
import admin.Utils;
import data.bonus.Bonus;
/**
* GameData is the class that will be used to keep track of the important game
* information, including the number of weeks passed, the lists of all/active
* contestants, and the number of weeks remaining.
*
* @author Graem Littleton, Ramesh Raj, Justin McDonald, Jonathan Demelo, Kevin
* Brightwell
*/
public class GameData extends Observable {
private int weeksRem, weeksPassed; // keep track of weeks remaining/weeks
// passed
private int numInitialContestants;
private int betAmount, totalAmount;
private boolean seasonStarted = false;
private boolean elimExists = false;
private String[] tribeNames = new String[2]; // string array storing both
// tribe names
private List<Contestant> allContestants;
private List<User> allUsers;
// store the current running version
private static GameData currentGame = null;
// store contestant who was cast off
private Contestant elimCont;
// used for asynchronous calls to notifyObservers()
private UpdateCall updateExec;
public enum UpdateTag {
START_SEASON, ADVANCE_WEEK, SET_TRIBE_NAMES,
ADD_CONTESTANT, REMOVE_CONTESTANT, CONTESTANT_CAST_OFF,
ADD_USER, REMOVE_USER,
FINAL_WEEK, END_GAME, ALLOCATE_POINTS
}
/**
* JSON Keys
*/
private static final String KEY_CONTESTANTS = "cons",
KEY_NUM_CONTEST = "cons_num",
KEY_USERS = "users",
KEY_WEEKS_REMAIN = "weeks_rem",
KEY_WEEKS_PASSED = "weeks_pass",
KEY_TRIBES = "tribes_arr",
KEY_SEASON_STARTED = "season_started",
KEY_BET_AMOUNT = "bet_amount",
KEY_POOL_TOTAL = "pool_total";
/**
* Constructor method that takes a set number of contestants. Will not
* proceed if numInitialContestants is NOT between 6 and 15, inclusive. Sets
* number of weeks passed to 0 and weeks remaining to number of contestants
* - 3.
*
* @param numInitialContestants
* number of contestants to be in game
*/
// TODO: Make throw exception, its not enough to return, the object is still
// created.
public GameData(int numInitialContestants) {
// check if within parameters
if (numInitialContestants > 15 || numInitialContestants < 6)
return; // if not, do not create GameData item
weeksRem = numInitialContestants - 2;
weeksPassed = 0;
setBetAmount(0);
this.numInitialContestants = numInitialContestants;
// containers for contestants and users
allContestants = new ArrayList<Contestant>(numInitialContestants);
allUsers = new ArrayList<User>(5);
currentGame = this;
}
// ----------------- ACCESSOR METHODS -----------------//
// ~~~~~~~~~~~~~~~~ CONTESTANT METHODS ~~~~~~~~~~~~~~~ //
/**
* getActiveContestants returns an array (list) of the contestants that are
* still competing in the game.
*
* @return The contestants active
*/
public List<Contestant> getActiveContestants() {
List<Contestant> active = new ArrayList<Contestant>(
allContestants.size());
for (Contestant c : allContestants) {
if ((c != null) && (!c.isCastOff()|| c.isToBeCast())) {
active.add(c);
}
}
return active;
}
/**
* getInitialContestants returns an integer of the number of initial
* contestants that are in the game.
*
* @return The current amount of contestants
*/
public int getInitialContestants() {
return numInitialContestants;
}
/**
* getNumCurrentContestants returns an integer of the number of contestants
* that are in the game.
*
* @return The current amount of contestants
*/
public int getNumCurrentContestants() {
return allContestants.size();
}
/**
* getAllContestants returns a list of all current and former contestants
* that are/have been involved with the game.
*
* @return this.allContestants
*/
public List<Contestant> getAllContestants() {
return allContestants;
}
/**
* getContestant takes the first and last name of a contestant as input and
* searches the array of current contestants for him/her. Returns
* information found in the Contestant class to the caller.
*
* @param first
* First name
* @param last
* Last name
* @return contestant or string object
*/
public Contestant getContestant(String first, String last) {
// loop through array
for (Contestant j : allContestants) {
if (first.equals(j.getFirstName()) && last.equals(j.getLastName())) { // ensure
// //
// match
// return info on player
return j;
}
}
// otherwise return message saying contestant is no longer/is not in the
// game
return null;
}
/**
* Get contestant based on unique id
*
* @param id
* an unique id
* @return the Contestant that matches id or null
*/
public Contestant getContestant(String id) {
int i = getContestantIndexID(id);
if (i >= 0)
return allContestants.get(i);
else
return null;
}
/**
* Adds a new contestant into the Game, this will maintain the list of
* contestants as sorted by ID.
*
* @param c
* New contestant, will not add if ID of contestant is null.
*/
public void addContestant(Contestant c) throws InvalidFieldException {
if (allContestants.size() == numInitialContestants) {
System.out.println("Too many contestants.");
return;
}
if (isContestantIDInUse(c.getID())) {
throw new InvalidFieldException(
InvalidFieldException.Field.CONT_ID_DUP,
"Contestant ID invald (in use)");
}
allContestants.add(c);
notifyAdd(UpdateTag.ADD_CONTESTANT);
}
/**
* removeContestant takes a Contestant object as input and attempts to
* remove it from the array of active contestants. Maintains order of data
*
* @param target
* Contestant to remove
*/
public void removeContestant(Contestant target) {
// is the contestant there?
allContestants.remove(target);
Collections.sort(allContestants);
notifyAdd(UpdateTag.REMOVE_CONTESTANT);
}
// ~~~~~~~~~~~~~~~~~~~ USER METHODS ~~~~~~~~~~~~~~~~~~ //
/**
* Gets the vector of all users.
*
* @return Vector containing all users.
*/
public List<User> getAllUsers() {
return allUsers;
}
/**
* getNumUsers returns an integer of the number of players
* that are in the game.
*
* @return The current amount of playerss
*/
public int getNumUsers() {
return allUsers.size();
}
/**
* Adds a user to the list of users.
*
* @param u
* New user to add.
* @throws InvalidFieldException
* Thrown if ID already in use.
*/
public void addUser(User u) throws InvalidFieldException {
if (isUserIDInUse(u.getID())) {
throw new InvalidFieldException(
InvalidFieldException.Field.CONT_ID_DUP,
"Contestant ID invald (in use)");
}
allUsers.add(u);
notifyAdd(UpdateTag.ADD_USER);
}
/**
* Removes a user from the list.
*
* @param u
* User to remove.
*/
public void removeUser(User u) {
allUsers.remove(u);
notifyAdd(UpdateTag.REMOVE_USER);
}
/**
* Gets a user from the stored users by ID.
*
* @param ID
* User ID of the User to get from the stored data.
* @return User if ID found, null otherwise.
*/
public User getUser(String ID) {
for (User u : allUsers) {
if (u.getID().equalsIgnoreCase(ID)) {
return u;
}
}
return null;
}
/**
* Iterates through all users on the list. Allocates points based off of
* weekly elimination pick.
*
* @param c
* Contestant that was cast off
*/
public void allocatePoints(Contestant c) {
Iterator<User> itr = allUsers.iterator();
User u;
while (itr.hasNext()) {
u = itr.next();
if (u.getWeeklyPick().equals(c)) {
if (this.isFinalWeek()) // final week
u.addPoints(40);
else // normal week
u.addPoints(20);
}
// if the end of the game and the person gets the right ultimate pick
if (u.getUltimatePick().equals(c) && this.isFinalWeek()){
u.addPoints(u.getUltimatePoints());
}
u.addPoints(u.getNumBonusAnswer() * 10); // add week's correct bonus questions
u.setNumBonusAnswer(0); // clears the number of questions
}
notifyAdd(UpdateTag.ALLOCATE_POINTS);
}
public List<Integer> determinePrizePool(){
List<Integer> tempList = new ArrayList<Integer>();
//attempt to be as precise as possible.
if (getNumUsers() <= 0){ // no users
return null;
} else if (getNumUsers() == 1) { // one user, he gets the whole pool
tempList.add(getTotalAmount());
return tempList;
} else if (getNumUsers() == 2) { // two users, first user gets 65% of the
//winnings, the rest goes to the second
tempList.add((int) (getTotalAmount()*0.65)); // first 65
tempList.add(getTotalAmount() - tempList.get(0)); // the rest
} else { // three or more users
// split is 60/30/10
tempList.add((int) (getTotalAmount()*0.60)); // first 60
// total amount - the first amount, which leaves 40% of the original amount
// 30% is now equivalent to 75% of the new amount
tempList.add((int) ((getTotalAmount()- tempList.get(0)) * 0.75));
// the total minus the first and second place winnings.
tempList.add(getTotalAmount() - tempList.get(0) - tempList.get(1));
}
return tempList;
}
/**
* Iterates through all players on the list, and determines the top three winners.
*
* @param u
* Player within the game.
*/
public List<User> determineWinners() {
Iterator<User> itr = allUsers.iterator();
User u;
User first = new User ();
User second = new User ();
User third = new User ();
first.setPoints(0);
second.setPoints(0);
third.setPoints(0);
while (itr.hasNext()) {
u = itr.next();
if (u.getPoints() > first.getPoints()) {
first = u;
} else if (u.getPoints() > second.getPoints()){
second = u;
} else if (u.getPoints() > third.getPoints()){
third = u;
}
}
List<User> tempList = new ArrayList<User>();
// the following removes any temporary user objects from the
// outputted list, in the case of less then three users
// participating.
if (first.getID() != null)
tempList.add(first);
if (second.getID() != null)
tempList.add(second);
if (third.getID() != null)
tempList.add(third);
return tempList;
}
/**
* getTribeName returns a String array with two entries: the name of the
* first tribe, and the name of the second tribe.
*
* @return String array tribe names
*/
public String[] getTribeNames() {
return tribeNames;
}
/**
* weeksLeft returns the number of weeks remaining before the game ends.
*
* @return this.weeksRem
*/
public int weeksLeft() {
return weeksRem;
}
/**
* Get the current week in play. Starts from Week 1.
*
* @return Current week
*/
public int getCurrentWeek() {
return weeksPassed + 1;
}
/**
* Checks if a season has been started
*
* @see startGame to set to true.
* @return true if a season has started(different from created)
*/
public boolean isSeasonStarted() {
return seasonStarted;
}
/**
* Checks if there are any more weeks remaining
*
* @return true if weeks remaining = 0
*/
public boolean isSeasonEnded() {
return weeksRem == 0;
}
/**
* Checks if there are any more weeks remaining
*
* @return true if weeks remaining = 1
*/
public boolean isFinalWeek() {
return weeksRem == 1;
}
// ----------------- MUTATOR METHODS ------------------//
/**
* TOOD:
*
* @param isActive
* @return
*/
public Contestant randomContestant(boolean isActive) {
List<Contestant> list = null;
if (isActive) {
list = getActiveContestants();
} else {
list = getAllContestants();
}
Random r = new Random();
int index = r.nextInt(list.size());
return list.get(index);
}
/**
* advanceWeek sets the number of weeksPassed to weeksPassed + 1.
*/
public void advanceWeek() {
if (elimExists == false)
return;
/* Fill weekly NULLs */
for (User u : allUsers) {
if (u.getWeeklyPick().isNull() || u.getWeeklyPick() == null) {
try {
u.setWeeklyPick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
/* Fill ultimate NULLs */
if (u.getUltimatePick().isNull()) {
try {
u.setUltimatePick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
}
allocatePoints(getElimCont());
Contestant nullC = new Contestant();
nullC.setNull();
/* clear all weekly picks */
for (User u : allUsers) {
try {
u.setWeeklyPick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
/* clear defunct ult picks */
if (u.getUltimatePick().getID().equals(getElimCont().getID())) {
try {
u.setUltimatePick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
}
}
getElimCont().castOff();
weeksRem -= 1; // reduce num of weeks remaining
weeksPassed += 1; // increment number of weeks passed
- notifyAdd(UpdateTag.ADVANCE_WEEK);
+ if (isFinalWeek())
+ notifyAdd(UpdateTag.FINAL_WEEK);
+ else if (isSeasonEnded())
+ notifyAdd(UpdateTag.END_GAME);
+ else
+ notifyAdd(UpdateTag.ADVANCE_WEEK);
}
/**
* startGame sets gameStarted to true, not allowing the admin to add any
* more players/Contestants to the pool/game.
*/
public void startSeason(int bet) {
this.setBetAmount(bet);
seasonStarted = true;
notifyAdd(UpdateTag.START_SEASON);
}
/**
* setTribeNames sets both tribe names accordingly and stores them in the
* tribeNames string array. Updates all contestants accordingly
*
* @param tribeOne
* name of tribe one
* @param tribeTwo
* name of tribe two
*/
public String[] setTribeNames(String tribeOne, String tribeTwo){
// temp tribe vars.
String oldT1 = tribeNames[0];
String oldT2 = tribeNames[1];
// set the new tribes (Contestant requires this)
tribeNames[0] = Utils.strCapitalize(tribeOne.toLowerCase().trim());
tribeNames[1] = Utils.strCapitalize(tribeTwo.toLowerCase().trim());
// update all tribes first..
for (Contestant c : allContestants) {
if (c.getTribe().equalsIgnoreCase(oldT1)) {
try {
c.setTribe(tribeOne);
} catch (InvalidFieldException e) {
}
} else if (c.getTribe().equalsIgnoreCase(oldT2)) {
try {
c.setTribe(tribeTwo);
} catch (InvalidFieldException e) {
}
}
}
notifyAdd(UpdateTag.SET_TRIBE_NAMES);
return tribeNames;
}
/**
* TODO:
*
* @return
*/
public boolean doesElimExist() {
return elimExists;
}
/**
* TODO:
*
* @param elimExists
*/
protected void setElimExists(boolean elimExists) {
this.elimExists = elimExists;
}
/**
* TODO:
*
* @return
*/
protected Contestant getElimCont() {
return elimCont;
}
/**
* TODO:
*
* @param elimCont
*/
protected void setElimCont(Contestant elimCont) {
this.elimCont = elimCont;
}
/**
* Casts a contestant from the game.
* @param castOff
*/
public void castOff(Contestant castOff) {
if (castOff.isCastOff()) // can't recast off..
return;
setElimCont(castOff);
setElimExists(true);
castOff.setCastDate(getCurrentWeek());
castOff.setToBeCast(true);
notifyAdd(UpdateTag.CONTESTANT_CAST_OFF);
}
/**
* Undoes the current contestant that would be cast off.
* @param castOff
*/
public void undoCastOff(Contestant castOff) {
castOff.setToBeCast(false);
castOff.setCastDate(-1);
setElimCont(null);
setElimExists(false);
}
// ----------------- HELPER METHODS ----------------- //
/**
* Helper method to get the index of a contestant ID in the
* activeContestants array
*
* @param searchID
* Search Contestant ID
* @return Index in activeContestants where ID is stored, else < 0.
*/
protected int getContestantIndexID(String searchID) {
return Utils.BinIDSearchSafe(allContestants, searchID);
}
/**
* Tells whether a Contestant ID is in use.
*
* @param id
* The Contestant ID is in use.
* @return True if in use.
*/
public boolean isContestantIDInUse(String id) {
return (getContestantIndexID(id) >= 0);
}
/**
* Tells whether a User ID is in use.
*
* @param id
* The Contestant ID is in use.
* @return True if in use.
*/
public boolean isUserIDInUse(String id) {
return (getUserIndexID(id) >= 0);
}
/**
* Gets a Users index in the stored list by ID. Uses a binary search for
* speed.
*
* @param searchID
* @return Index in the list, index <0 if not found.
*/
protected int getUserIndexID(String searchID) {
return Utils.BinIDSearchSafe(allUsers, searchID);
}
/**
* set the bet amount.
*
* @param bet amount
*/
public void setBetAmount(int betAmount) {
this.betAmount = betAmount;
}
/**
* get the bet amount.
*
* @return bet amount
*/
public int getBetAmount() {
return betAmount;
}
/**
* get the total bet pool.
*
* @return the bet amount * the number of users * the number of game weeks
*/
public int getTotalAmount(){
return betAmount*getNumUsers()*(getCurrentWeek()+weeksLeft());
}
/**
* Returns the currently stored Game, this removed need to reference the
* game data all the time. But also allows objects to read data, cleanly.
*
* @return Currently started game, null if none present.
*/
public static GameData getCurrentGame() {
return GameData.currentGame;
}
/**
* Nulls the current game stored, allows a new game to start.
*/
public void endCurrentGame() {
GameData.currentGame = null;
Bonus.deleteAllQuestions();
notifyAdd(UpdateTag.END_GAME);
JSONUtils.resetSeason();
}
/**
* toString returns a string of the contestant's information in JSON format.
*/
public String toString() {
return new String("GameData<WR:\"" + weeksRem + "\"" + ", WP:\""
+ weeksPassed + "\"" + ", #C:\"" + numInitialContestants + "\""
+ ", SS: " + "\"" + seasonStarted + "\"" + ", TN: {" + "\""
+ tribeNames[0] + "\", \"" + tribeNames[1] + "\"}>");
}
/**
* Convert GameData to a JSON object
*
* @return a JSONObject with all the relevant data
* @throws JSONException
*/
public JSONObject toJSONObject() throws ParseException {
JSONObject obj = new JSONObject();
obj.put(KEY_NUM_CONTEST, new Integer(numInitialContestants));
JSONArray cons = new JSONArray();
for (Object o : allContestants) {
if (o != null)
cons.add(((Contestant) o).toJSONObject());
}
JSONArray users = new JSONArray();
for (Object o : allUsers) {
if (o != null)
users.add(((User) o).toJSONObject());
}
JSONArray ts = new JSONArray();
ts.add(tribeNames[0]);
ts.add(tribeNames[1]);
obj.put(KEY_CONTESTANTS, cons);
obj.put(KEY_USERS, users);
obj.put(KEY_TRIBES, ts);
obj.put(KEY_WEEKS_REMAIN, weeksRem);
obj.put(KEY_WEEKS_PASSED, weeksPassed);
obj.put(KEY_SEASON_STARTED, seasonStarted);
if(seasonStarted){
obj.put(KEY_BET_AMOUNT, betAmount);
obj.put(KEY_POOL_TOTAL, totalAmount);
}
return obj;
}
/**
* Update GameData with values from JSONObject
*
* @param obj
* a JSONObject that contains all the values
* @throws JSONException
*/
public void fromJSONObject(JSONObject obj) throws ParseException {
numInitialContestants = ((Number) obj.get(KEY_NUM_CONTEST)).intValue();
// tribes
JSONArray ts = (JSONArray) obj.get(KEY_TRIBES);
setTribeNames((String) ts.get(0), (String) ts.get(1));
// week info:
weeksRem = Utils.numToInt(obj.get(KEY_WEEKS_REMAIN));
weeksPassed = Utils.numToInt(obj.get(KEY_WEEKS_PASSED));
seasonStarted = (Boolean) obj.get(KEY_SEASON_STARTED);
if(seasonStarted){
betAmount = Utils.numToInt(obj.get(KEY_BET_AMOUNT));
totalAmount = Utils.numToInt(obj.get(KEY_POOL_TOTAL));
System.out.println(betAmount + " " + totalAmount);
}
// Contestants must be loaded before users, but after others!
allContestants = new ArrayList<Contestant>(numInitialContestants);
// load the contestant array.
JSONArray cons = (JSONArray) obj.get(KEY_CONTESTANTS);
for (int i = 0; i < cons.size(); i++) {
Contestant c = new Contestant();
c.fromJSONObject((JSONObject)cons.get(i));
try {
addContestant(c);
} catch (InvalidFieldException ie) {
}
}
// users:
JSONArray users = (JSONArray) obj.get(KEY_USERS);
allUsers = new ArrayList<User>(users.size());
for (int i = 0; i < users.size(); i++) {
User u = new User();
u.fromJSONObject((JSONObject)users.get(i));
try {
addUser(u);
} catch (InvalidFieldException ie) {
}
}
notifyAdd();
}
/**
* Used by SeasonCreate to create a new season.
*
* @param num
*/
public static void initSeason(int num) {
currentGame = new GameData(num);
}
/**
* intGameData reads in a data file and builds a GameData object out of it,
* returning it to the user.
*
* @param inputFile
* file to be read in
* @return GameData object made out of file or null if season not created
*
*/
public static GameData initGameData() {
JSONObject json;
try {
json = JSONUtils.readFile(JSONUtils.pathGame);
} catch (FileNotFoundException e) {
return currentGame;
}
currentGame = new GameData(
Utils.numToInt(json.get(KEY_NUM_CONTEST)));
// TODO: Combine?
try {
GameData.getCurrentGame().fromJSONObject(json);
} catch (ParseException e) {
e.printStackTrace();
}
Bonus.initBonus();
return (GameData) currentGame;
}
/**
* Write all DATA into file
*/
public void writeData() {
try {
JSONUtils.writeJSON(JSONUtils.pathGame, this.toJSONObject());
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
GameData g = new GameData(6);
String[] tribes = new String[] { "banana", "apple" };
g.setTribeNames(tribes[0], tribes[1]);
Contestant c1 = null, c2 = null;
try {
c1 = new Contestant("a2", "Al", "Sd", tribes[1]);
c2 = new Contestant("as", "John", "Silver", tribes[0]);
} catch (InvalidFieldException e) {
// wont happen.
}
try {
g.addContestant(c1);
g.addContestant(c2);
} catch (InvalidFieldException ie) {
}
g.startSeason(5);
User u1;
try {
u1 = new User("First", "last", "flast");
User u2 = new User("Firsto", "lasto", "flasto");
g.addUser(u1);
g.addUser(u2);
u1.setPoints(10);
u2.setPoints(1);
} catch (InvalidFieldException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
System.out.println(g.toJSONObject().toString());
} catch (ParseException e1) {
e1.printStackTrace();
}
}
/**
* Small class used for removing parallel calls to do the same
* notification. The update system accounts for multiple modifications
* in one update call, so this means those methods are only called once.
* @author Kevin Brightwell
*/
private class UpdateCall implements Runnable {
public EnumSet<UpdateTag> mods = EnumSet.noneOf(UpdateTag.class);
public boolean done = false;
@Override
public void run() {
setChanged();
notifyObservers(mods);
done = true;
}
}
/**
* Adds a set of {@link GameData.UpdateTag}s to the next update call. This
* method in conjunction with {@link GameData.UpdateCall} works to remove
* excess method executions.
* @param tags Tags to add to the next call.
*/
public void notifyAdd(UpdateTag... tags) {
if (updateExec == null || updateExec.done) {
updateExec = new UpdateCall();
SwingUtilities.invokeLater(updateExec);
}
for (UpdateTag ut: tags) {
if (!updateExec.mods.contains(ut))
updateExec.mods.add(ut);
}
}
/**
* Creates a EnumSet of the tags passed, allowing for flexible notions
* of multiple tags sent.
* @param tags Sets the flags of the set.
* @return EnumSet containing the tags passed.
*/
/*private EnumSet updateTagSet(UpdateTag... tags) {
EnumSet set =
new EnumSet(UpdateTag.class);
return set.of(tags);
}*/
}
| true | true | public void advanceWeek() {
if (elimExists == false)
return;
/* Fill weekly NULLs */
for (User u : allUsers) {
if (u.getWeeklyPick().isNull() || u.getWeeklyPick() == null) {
try {
u.setWeeklyPick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
/* Fill ultimate NULLs */
if (u.getUltimatePick().isNull()) {
try {
u.setUltimatePick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
}
allocatePoints(getElimCont());
Contestant nullC = new Contestant();
nullC.setNull();
/* clear all weekly picks */
for (User u : allUsers) {
try {
u.setWeeklyPick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
/* clear defunct ult picks */
if (u.getUltimatePick().getID().equals(getElimCont().getID())) {
try {
u.setUltimatePick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
}
}
getElimCont().castOff();
weeksRem -= 1; // reduce num of weeks remaining
weeksPassed += 1; // increment number of weeks passed
notifyAdd(UpdateTag.ADVANCE_WEEK);
}
| public void advanceWeek() {
if (elimExists == false)
return;
/* Fill weekly NULLs */
for (User u : allUsers) {
if (u.getWeeklyPick().isNull() || u.getWeeklyPick() == null) {
try {
u.setWeeklyPick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
/* Fill ultimate NULLs */
if (u.getUltimatePick().isNull()) {
try {
u.setUltimatePick(randomContestant(true));
} catch (InvalidFieldException e) {
} // wont happen
}
}
allocatePoints(getElimCont());
Contestant nullC = new Contestant();
nullC.setNull();
/* clear all weekly picks */
for (User u : allUsers) {
try {
u.setWeeklyPick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
/* clear defunct ult picks */
if (u.getUltimatePick().getID().equals(getElimCont().getID())) {
try {
u.setUltimatePick(nullC);
} catch (InvalidFieldException e) {
} // wont happen
}
}
getElimCont().castOff();
weeksRem -= 1; // reduce num of weeks remaining
weeksPassed += 1; // increment number of weeks passed
if (isFinalWeek())
notifyAdd(UpdateTag.FINAL_WEEK);
else if (isSeasonEnded())
notifyAdd(UpdateTag.END_GAME);
else
notifyAdd(UpdateTag.ADVANCE_WEEK);
}
|
diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java b/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java
index d9eada4a4..a421550de 100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReaderReopen.java
@@ -1,1277 +1,1278 @@
package org.apache.lucene.index;
/**
* 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.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.DefaultSimilarity;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.search.SimilarityProvider;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BitVector;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
public class TestIndexReaderReopen extends LuceneTestCase {
public void testReopen() throws Exception {
final Directory dir1 = newDirectory();
createIndex(random, dir1, false);
performDefaultTests(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir1);
}
@Override
protected IndexReader openReader() throws IOException {
return IndexReader.open(dir1, false);
}
});
dir1.close();
final Directory dir2 = newDirectory();
createIndex(random, dir2, true);
performDefaultTests(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir2);
}
@Override
protected IndexReader openReader() throws IOException {
return IndexReader.open(dir2, false);
}
});
dir2.close();
}
public void testParallelReaderReopen() throws Exception {
final Directory dir1 = newDirectory();
createIndex(random, dir1, true);
final Directory dir2 = newDirectory();
createIndex(random, dir2, true);
performDefaultTests(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir1);
TestIndexReaderReopen.modifyIndex(i, dir2);
}
@Override
protected IndexReader openReader() throws IOException {
ParallelReader pr = new ParallelReader();
pr.add(IndexReader.open(dir1, false));
pr.add(IndexReader.open(dir2, false));
return pr;
}
});
dir1.close();
dir2.close();
final Directory dir3 = newDirectory();
createIndex(random, dir3, true);
final Directory dir4 = newDirectory();
createIndex(random, dir4, true);
performTestsWithExceptionInReopen(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir3);
TestIndexReaderReopen.modifyIndex(i, dir4);
}
@Override
protected IndexReader openReader() throws IOException {
ParallelReader pr = new ParallelReader();
pr.add(IndexReader.open(dir3, false));
pr.add(IndexReader.open(dir4, false));
// Does not implement reopen, so
// hits exception:
pr.add(new FilterIndexReader(IndexReader.open(dir3, false)));
return pr;
}
});
dir3.close();
dir4.close();
}
// LUCENE-1228: IndexWriter.commit() does not update the index version
// populate an index in iterations.
// at the end of every iteration, commit the index and reopen/recreate the reader.
// in each iteration verify the work of previous iteration.
// try this once with reopen once recreate, on both RAMDir and FSDir.
public void testCommitReopen () throws IOException {
Directory dir = newDirectory();
doTestReopenWithCommit(random, dir, true);
dir.close();
}
public void testCommitRecreate () throws IOException {
Directory dir = newDirectory();
doTestReopenWithCommit(random, dir, false);
dir.close();
}
private void doTestReopenWithCommit (Random random, Directory dir, boolean withReopen) throws IOException {
IndexWriter iwriter = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)).setOpenMode(
OpenMode.CREATE).setMergeScheduler(new SerialMergeScheduler()).setMergePolicy(newLogMergePolicy()));
iwriter.commit();
IndexReader reader = IndexReader.open(dir, false);
try {
int M = 3;
for (int i=0; i<4; i++) {
for (int j=0; j<M; j++) {
Document doc = new Document();
doc.add(newField("id", i+"_"+j, Store.YES, Index.NOT_ANALYZED));
doc.add(newField("id2", i+"_"+j, Store.YES, Index.NOT_ANALYZED_NO_NORMS));
doc.add(newField("id3", i+"_"+j, Store.YES, Index.NO));
iwriter.addDocument(doc);
if (i>0) {
int k = i-1;
int n = j + k*M;
Document prevItereationDoc = reader.document(n);
assertNotNull(prevItereationDoc);
String id = prevItereationDoc.get("id");
assertEquals(k+"_"+j, id);
}
}
iwriter.commit();
if (withReopen) {
// reopen
IndexReader r2 = reader.reopen();
if (reader != r2) {
reader.close();
reader = r2;
}
} else {
// recreate
reader.close();
reader = IndexReader.open(dir, false);
}
}
} finally {
iwriter.close();
reader.close();
}
}
public void testMultiReaderReopen() throws Exception {
final Directory dir1 = newDirectory();
createIndex(random, dir1, true);
final Directory dir2 = newDirectory();
createIndex(random, dir2, true);
performDefaultTests(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir1);
TestIndexReaderReopen.modifyIndex(i, dir2);
}
@Override
protected IndexReader openReader() throws IOException {
return new MultiReader(IndexReader.open(dir1, false),
IndexReader.open(dir2, false));
}
});
dir1.close();
dir2.close();
final Directory dir3 = newDirectory();
createIndex(random, dir3, true);
final Directory dir4 = newDirectory();
createIndex(random, dir4, true);
performTestsWithExceptionInReopen(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
TestIndexReaderReopen.modifyIndex(i, dir3);
TestIndexReaderReopen.modifyIndex(i, dir4);
}
@Override
protected IndexReader openReader() throws IOException {
return new MultiReader(IndexReader.open(dir3, false),
IndexReader.open(dir4, false),
// Does not implement reopen, so
// hits exception:
new FilterIndexReader(IndexReader.open(dir3, false)));
}
});
dir3.close();
dir4.close();
}
public void testMixedReaders() throws Exception {
final Directory dir1 = newDirectory();
createIndex(random, dir1, true);
final Directory dir2 = newDirectory();
createIndex(random, dir2, true);
final Directory dir3 = newDirectory();
createIndex(random, dir3, false);
final Directory dir4 = newDirectory();
createIndex(random, dir4, true);
final Directory dir5 = newDirectory();
createIndex(random, dir5, false);
performDefaultTests(new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
// only change norms in this index to maintain the same number of docs for each of ParallelReader's subreaders
if (i == 1) TestIndexReaderReopen.modifyIndex(i, dir1);
TestIndexReaderReopen.modifyIndex(i, dir4);
TestIndexReaderReopen.modifyIndex(i, dir5);
}
@Override
protected IndexReader openReader() throws IOException {
ParallelReader pr = new ParallelReader();
pr.add(IndexReader.open(dir1, false));
pr.add(IndexReader.open(dir2, false));
MultiReader mr = new MultiReader(IndexReader.open(dir3, false), IndexReader.open(dir4, false));
return new MultiReader(pr, mr, IndexReader.open(dir5, false));
}
});
dir1.close();
dir2.close();
dir3.close();
dir4.close();
dir5.close();
}
private void performDefaultTests(TestReopen test) throws Exception {
IndexReader index1 = test.openReader();
IndexReader index2 = test.openReader();
TestIndexReader.assertIndexEquals(index1, index2);
// verify that reopen() does not return a new reader instance
// in case the index has no changes
ReaderCouple couple = refreshReader(index2, false);
assertTrue(couple.refreshedReader == index2);
couple = refreshReader(index2, test, 0, true);
index1.close();
index1 = couple.newReader;
IndexReader index2_refreshed = couple.refreshedReader;
index2.close();
// test if refreshed reader and newly opened reader return equal results
TestIndexReader.assertIndexEquals(index1, index2_refreshed);
index2_refreshed.close();
assertReaderClosed(index2, true, true);
assertReaderClosed(index2_refreshed, true, true);
index2 = test.openReader();
for (int i = 1; i < 4; i++) {
index1.close();
couple = refreshReader(index2, test, i, true);
// refresh IndexReader
index2.close();
index2 = couple.refreshedReader;
index1 = couple.newReader;
TestIndexReader.assertIndexEquals(index1, index2);
}
index1.close();
index2.close();
assertReaderClosed(index1, true, true);
assertReaderClosed(index2, true, true);
}
public void testReferenceCounting() throws IOException {
for (int mode = 0; mode < 4; mode++) {
Directory dir1 = newDirectory();
createIndex(random, dir1, true);
IndexReader reader0 = IndexReader.open(dir1, false);
assertRefCountEquals(1, reader0);
assertTrue(reader0 instanceof DirectoryReader);
IndexReader[] subReaders0 = reader0.getSequentialSubReaders();
for (int i = 0; i < subReaders0.length; i++) {
assertRefCountEquals(1, subReaders0[i]);
}
// delete first document, so that only one of the subReaders have to be re-opened
IndexReader modifier = IndexReader.open(dir1, false);
modifier.deleteDocument(0);
modifier.close();
IndexReader reader1 = refreshReader(reader0, true).refreshedReader;
assertTrue(reader1 instanceof DirectoryReader);
IndexReader[] subReaders1 = reader1.getSequentialSubReaders();
assertEquals(subReaders0.length, subReaders1.length);
for (int i = 0; i < subReaders0.length; i++) {
if (subReaders0[i] != subReaders1[i]) {
assertRefCountEquals(1, subReaders0[i]);
assertRefCountEquals(1, subReaders1[i]);
} else {
assertRefCountEquals(2, subReaders0[i]);
}
}
// delete first document, so that only one of the subReaders have to be re-opened
modifier = IndexReader.open(dir1, false);
modifier.deleteDocument(1);
modifier.close();
IndexReader reader2 = refreshReader(reader1, true).refreshedReader;
assertTrue(reader2 instanceof DirectoryReader);
IndexReader[] subReaders2 = reader2.getSequentialSubReaders();
assertEquals(subReaders1.length, subReaders2.length);
for (int i = 0; i < subReaders2.length; i++) {
if (subReaders2[i] == subReaders1[i]) {
if (subReaders1[i] == subReaders0[i]) {
assertRefCountEquals(3, subReaders2[i]);
} else {
assertRefCountEquals(2, subReaders2[i]);
}
} else {
assertRefCountEquals(1, subReaders2[i]);
if (subReaders0[i] == subReaders1[i]) {
assertRefCountEquals(2, subReaders2[i]);
assertRefCountEquals(2, subReaders0[i]);
} else {
assertRefCountEquals(1, subReaders0[i]);
assertRefCountEquals(1, subReaders1[i]);
}
}
}
IndexReader reader3 = refreshReader(reader0, true).refreshedReader;
assertTrue(reader3 instanceof DirectoryReader);
IndexReader[] subReaders3 = reader3.getSequentialSubReaders();
assertEquals(subReaders3.length, subReaders0.length);
// try some permutations
switch (mode) {
case 0:
reader0.close();
reader1.close();
reader2.close();
reader3.close();
break;
case 1:
reader3.close();
reader2.close();
reader1.close();
reader0.close();
break;
case 2:
reader2.close();
reader3.close();
reader0.close();
reader1.close();
break;
case 3:
reader1.close();
reader3.close();
reader2.close();
reader0.close();
break;
}
assertReaderClosed(reader0, true, true);
assertReaderClosed(reader1, true, true);
assertReaderClosed(reader2, true, true);
assertReaderClosed(reader3, true, true);
dir1.close();
}
}
public void testReferenceCountingMultiReader() throws IOException {
for (int mode = 0; mode <=1; mode++) {
Directory dir1 = newDirectory();
createIndex(random, dir1, false);
Directory dir2 = newDirectory();
createIndex(random, dir2, true);
IndexReader reader1 = IndexReader.open(dir1, false);
assertRefCountEquals(1, reader1);
IndexReader initReader2 = IndexReader.open(dir2, false);
IndexReader multiReader1 = new MultiReader(new IndexReader[] {reader1, initReader2}, (mode == 0));
modifyIndex(0, dir2);
assertRefCountEquals(1 + mode, reader1);
IndexReader multiReader2 = multiReader1.reopen();
// index1 hasn't changed, so multiReader2 should share reader1 now with multiReader1
assertRefCountEquals(2 + mode, reader1);
modifyIndex(0, dir1);
IndexReader reader2 = reader1.reopen();
assertRefCountEquals(2 + mode, reader1);
if (mode == 1) {
initReader2.close();
}
modifyIndex(1, dir1);
IndexReader reader3 = reader2.reopen();
assertRefCountEquals(2 + mode, reader1);
assertRefCountEquals(1, reader2);
multiReader1.close();
assertRefCountEquals(1 + mode, reader1);
multiReader1.close();
assertRefCountEquals(1 + mode, reader1);
if (mode == 1) {
initReader2.close();
}
reader1.close();
assertRefCountEquals(1, reader1);
multiReader2.close();
assertRefCountEquals(0, reader1);
multiReader2.close();
assertRefCountEquals(0, reader1);
reader3.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, false);
reader2.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, false);
reader2.close();
assertRefCountEquals(0, reader1);
reader3.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, true);
dir1.close();
dir2.close();
}
}
public void testReferenceCountingParallelReader() throws IOException {
for (int mode = 0; mode <=1; mode++) {
Directory dir1 = newDirectory();
createIndex(random, dir1, false);
Directory dir2 = newDirectory();
createIndex(random, dir2, true);
IndexReader reader1 = IndexReader.open(dir1, false);
assertRefCountEquals(1, reader1);
ParallelReader parallelReader1 = new ParallelReader(mode == 0);
parallelReader1.add(reader1);
IndexReader initReader2 = IndexReader.open(dir2, false);
parallelReader1.add(initReader2);
modifyIndex(1, dir2);
assertRefCountEquals(1 + mode, reader1);
IndexReader parallelReader2 = parallelReader1.reopen();
// index1 hasn't changed, so parallelReader2 should share reader1 now with multiReader1
assertRefCountEquals(2 + mode, reader1);
modifyIndex(0, dir1);
modifyIndex(0, dir2);
IndexReader reader2 = reader1.reopen();
assertRefCountEquals(2 + mode, reader1);
if (mode == 1) {
initReader2.close();
}
modifyIndex(4, dir1);
IndexReader reader3 = reader2.reopen();
assertRefCountEquals(2 + mode, reader1);
assertRefCountEquals(1, reader2);
parallelReader1.close();
assertRefCountEquals(1 + mode, reader1);
parallelReader1.close();
assertRefCountEquals(1 + mode, reader1);
if (mode == 1) {
initReader2.close();
}
reader1.close();
assertRefCountEquals(1, reader1);
parallelReader2.close();
assertRefCountEquals(0, reader1);
parallelReader2.close();
assertRefCountEquals(0, reader1);
reader3.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, false);
reader2.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, false);
reader2.close();
assertRefCountEquals(0, reader1);
reader3.close();
assertRefCountEquals(0, reader1);
assertReaderClosed(reader1, true, true);
dir1.close();
dir2.close();
}
}
public void testNormsRefCounting() throws IOException {
Directory dir1 = newDirectory();
createIndex(random, dir1, false);
IndexReader reader1 = IndexReader.open(dir1, false);
SegmentReader segmentReader1 = getOnlySegmentReader(reader1);
IndexReader modifier = IndexReader.open(dir1, false);
modifier.deleteDocument(0);
modifier.close();
IndexReader reader2 = reader1.reopen();
modifier = IndexReader.open(dir1, false);
Similarity sim = new DefaultSimilarity();
modifier.setNorm(1, "field1", sim.encodeNormValue(50f));
modifier.setNorm(1, "field2", sim.encodeNormValue(50f));
modifier.close();
IndexReader reader3 = reader2.reopen();
SegmentReader segmentReader3 = getOnlySegmentReader(reader3);
modifier = IndexReader.open(dir1, false);
modifier.deleteDocument(2);
modifier.close();
IndexReader reader4 = reader3.reopen();
modifier = IndexReader.open(dir1, false);
modifier.deleteDocument(3);
modifier.close();
IndexReader reader5 = reader3.reopen();
// Now reader2-reader5 references reader1. reader1 and reader2
// share the same norms. reader3, reader4, reader5 also share norms.
assertRefCountEquals(1, reader1);
assertFalse(segmentReader1.normsClosed());
reader1.close();
assertRefCountEquals(0, reader1);
assertFalse(segmentReader1.normsClosed());
reader2.close();
assertRefCountEquals(0, reader1);
// now the norms for field1 and field2 should be closed
assertTrue(segmentReader1.normsClosed("field1"));
assertTrue(segmentReader1.normsClosed("field2"));
// but the norms for field3 and field4 should still be open
assertFalse(segmentReader1.normsClosed("field3"));
assertFalse(segmentReader1.normsClosed("field4"));
reader3.close();
assertRefCountEquals(0, reader1);
assertFalse(segmentReader3.normsClosed());
reader5.close();
assertRefCountEquals(0, reader1);
assertFalse(segmentReader3.normsClosed());
reader4.close();
assertRefCountEquals(0, reader1);
// and now all norms that reader1 used should be closed
assertTrue(segmentReader1.normsClosed());
// now that reader3, reader4 and reader5 are closed,
// the norms that those three readers shared should be
// closed as well
assertTrue(segmentReader3.normsClosed());
dir1.close();
}
private void performTestsWithExceptionInReopen(TestReopen test) throws Exception {
IndexReader index1 = test.openReader();
IndexReader index2 = test.openReader();
TestIndexReader.assertIndexEquals(index1, index2);
try {
refreshReader(index1, test, 0, true);
fail("Expected exception not thrown.");
} catch (Exception e) {
// expected exception
}
// index2 should still be usable and unaffected by the failed reopen() call
TestIndexReader.assertIndexEquals(index1, index2);
index1.close();
index2.close();
}
public void testThreadSafety() throws Exception {
final Directory dir = newDirectory();
- final int n = atLeast(30);
+ // NOTE: this also controls the number of threads!
+ final int n = _TestUtil.nextInt(random, 20, 40);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
for (int i = 0; i < n; i++) {
writer.addDocument(createDocument(i, 3));
}
writer.optimize();
writer.close();
final TestReopen test = new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
if (i % 3 == 0) {
IndexReader modifier = IndexReader.open(dir, false);
Similarity sim = new DefaultSimilarity();
modifier.setNorm(i, "field1", sim.encodeNormValue(50f));
modifier.close();
} else if (i % 3 == 1) {
IndexReader modifier = IndexReader.open(dir, false);
modifier.deleteDocument(i % modifier.maxDoc());
modifier.close();
} else {
IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
modifier.addDocument(createDocument(n + i, 6));
modifier.close();
}
}
@Override
protected IndexReader openReader() throws IOException {
return IndexReader.open(dir, false);
}
};
final List<ReaderCouple> readers = Collections.synchronizedList(new ArrayList<ReaderCouple>());
IndexReader firstReader = IndexReader.open(dir, false);
IndexReader reader = firstReader;
final Random rnd = random;
ReaderThread[] threads = new ReaderThread[n];
final Set<IndexReader> readersToClose = Collections.synchronizedSet(new HashSet<IndexReader>());
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
IndexReader refreshed = reader.reopen();
if (refreshed != reader) {
readersToClose.add(reader);
}
reader = refreshed;
}
final IndexReader r = reader;
final int index = i;
ReaderThreadTask task;
if (i < 4 || (i >=10 && i < 14) || i > 18) {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
if (index % 2 == 0) {
// refresh reader synchronized
ReaderCouple c = (refreshReader(r, test, index, true));
readersToClose.add(c.newReader);
readersToClose.add(c.refreshedReader);
readers.add(c);
// prevent too many readers
break;
} else {
// not synchronized
IndexReader refreshed = r.reopen();
IndexSearcher searcher = newSearcher(refreshed);
ScoreDoc[] hits = searcher.search(
new TermQuery(new Term("field1", "a" + rnd.nextInt(refreshed.maxDoc()))),
null, 1000).scoreDocs;
if (hits.length > 0) {
searcher.doc(hits[0].doc);
}
searcher.close();
if (refreshed != r) {
refreshed.close();
}
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
} else {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
int numReaders = readers.size();
if (numReaders > 0) {
ReaderCouple c = readers.get(rnd.nextInt(numReaders));
TestIndexReader.assertIndexEquals(c.newReader, c.refreshedReader);
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
}
threads[i] = new ReaderThread(task);
threads[i].start();
}
synchronized(this) {
wait(1000);
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].stopThread();
}
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].join();
if (threads[i].error != null) {
String msg = "Error occurred in thread " + threads[i].getName() + ":\n" + threads[i].error.getMessage();
fail(msg);
}
}
}
for (final IndexReader readerToClose : readersToClose) {
readerToClose.close();
}
firstReader.close();
reader.close();
for (final IndexReader readerToClose : readersToClose) {
assertReaderClosed(readerToClose, true, true);
}
assertReaderClosed(reader, true, true);
assertReaderClosed(firstReader, true, true);
dir.close();
}
private static class ReaderCouple {
ReaderCouple(IndexReader r1, IndexReader r2) {
newReader = r1;
refreshedReader = r2;
}
IndexReader newReader;
IndexReader refreshedReader;
}
private abstract static class ReaderThreadTask {
protected volatile boolean stopped;
public void stop() {
this.stopped = true;
}
public abstract void run() throws Exception;
}
private static class ReaderThread extends Thread {
private ReaderThreadTask task;
private Throwable error;
ReaderThread(ReaderThreadTask task) {
this.task = task;
}
public void stopThread() {
this.task.stop();
}
@Override
public void run() {
try {
this.task.run();
} catch (Throwable r) {
r.printStackTrace(System.out);
this.error = r;
}
}
}
private Object createReaderMutex = new Object();
private ReaderCouple refreshReader(IndexReader reader, boolean hasChanges) throws IOException {
return refreshReader(reader, null, -1, hasChanges);
}
ReaderCouple refreshReader(IndexReader reader, TestReopen test, int modify, boolean hasChanges) throws IOException {
synchronized (createReaderMutex) {
IndexReader r = null;
if (test != null) {
test.modifyIndex(modify);
r = test.openReader();
}
IndexReader refreshed = null;
try {
refreshed = reader.reopen();
} finally {
if (refreshed == null && r != null) {
// Hit exception -- close opened reader
r.close();
}
}
if (hasChanges) {
if (refreshed == reader) {
fail("No new IndexReader instance created during refresh.");
}
} else {
if (refreshed != reader) {
fail("New IndexReader instance created during refresh even though index had no changes.");
}
}
return new ReaderCouple(r, refreshed);
}
}
public static void createIndex(Random random, Directory dir, boolean multiSegment) throws IOException {
IndexWriter.unlock(dir);
IndexWriter w = new IndexWriter(dir, LuceneTestCase.newIndexWriterConfig(random,
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 100; i++) {
w.addDocument(createDocument(i, 4));
if (multiSegment && (i % 10) == 0) {
w.commit();
}
}
if (!multiSegment) {
w.optimize();
}
w.close();
IndexReader r = IndexReader.open(dir, false);
if (multiSegment) {
assertTrue(r.getSequentialSubReaders().length > 1);
} else {
assertTrue(r.getSequentialSubReaders().length == 1);
}
r.close();
}
public static Document createDocument(int n, int numFields) {
StringBuilder sb = new StringBuilder();
Document doc = new Document();
sb.append("a");
sb.append(n);
doc.add(new Field("field1", sb.toString(), Store.YES, Index.ANALYZED));
doc.add(new Field("fielda", sb.toString(), Store.YES, Index.NOT_ANALYZED_NO_NORMS));
doc.add(new Field("fieldb", sb.toString(), Store.YES, Index.NO));
sb.append(" b");
sb.append(n);
for (int i = 1; i < numFields; i++) {
doc.add(new Field("field" + (i+1), sb.toString(), Store.YES, Index.ANALYZED));
}
return doc;
}
static void modifyIndex(int i, Directory dir) throws IOException {
switch (i) {
case 0: {
if (VERBOSE) {
System.out.println("TEST: modify index");
}
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)));
w.setInfoStream(VERBOSE ? System.out : null);
w.deleteDocuments(new Term("field2", "a11"));
w.deleteDocuments(new Term("field2", "b30"));
w.close();
break;
}
case 1: {
IndexReader reader = IndexReader.open(dir, false);
Similarity sim = new DefaultSimilarity();
reader.setNorm(4, "field1", sim.encodeNormValue(123f));
reader.setNorm(44, "field2", sim.encodeNormValue(222f));
reader.setNorm(44, "field4", sim.encodeNormValue(22f));
reader.close();
break;
}
case 2: {
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)));
w.optimize();
w.close();
break;
}
case 3: {
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)));
w.addDocument(createDocument(101, 4));
w.optimize();
w.addDocument(createDocument(102, 4));
w.addDocument(createDocument(103, 4));
w.close();
break;
}
case 4: {
IndexReader reader = IndexReader.open(dir, false);
Similarity sim = new DefaultSimilarity();
reader.setNorm(5, "field1", sim.encodeNormValue(123f));
reader.setNorm(55, "field2", sim.encodeNormValue(222f));
reader.close();
break;
}
case 5: {
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)));
w.addDocument(createDocument(101, 4));
w.close();
break;
}
}
}
private void assertReaderClosed(IndexReader reader, boolean checkSubReaders, boolean checkNormsClosed) {
assertEquals(0, reader.getRefCount());
if (checkNormsClosed && reader instanceof SegmentReader) {
assertTrue(((SegmentReader) reader).normsClosed());
}
if (checkSubReaders) {
if (reader instanceof DirectoryReader) {
IndexReader[] subReaders = reader.getSequentialSubReaders();
for (int i = 0; i < subReaders.length; i++) {
assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed);
}
}
if (reader instanceof MultiReader) {
IndexReader[] subReaders = reader.getSequentialSubReaders();
for (int i = 0; i < subReaders.length; i++) {
assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed);
}
}
if (reader instanceof ParallelReader) {
IndexReader[] subReaders = ((ParallelReader) reader).getSubReaders();
for (int i = 0; i < subReaders.length; i++) {
assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed);
}
}
}
}
/*
private void assertReaderOpen(IndexReader reader) {
reader.ensureOpen();
if (reader instanceof DirectoryReader) {
IndexReader[] subReaders = reader.getSequentialSubReaders();
for (int i = 0; i < subReaders.length; i++) {
assertReaderOpen(subReaders[i]);
}
}
}
*/
private void assertRefCountEquals(int refCount, IndexReader reader) {
assertEquals("Reader has wrong refCount value.", refCount, reader.getRefCount());
}
private abstract static class TestReopen {
protected abstract IndexReader openReader() throws IOException;
protected abstract void modifyIndex(int i) throws IOException;
}
public void testCloseOrig() throws Throwable {
Directory dir = newDirectory();
createIndex(random, dir, false);
IndexReader r1 = IndexReader.open(dir, false);
IndexReader r2 = IndexReader.open(dir, false);
r2.deleteDocument(0);
r2.close();
IndexReader r3 = r1.reopen();
assertTrue(r1 != r3);
r1.close();
try {
r1.document(2);
fail("did not hit exception");
} catch (AlreadyClosedException ace) {
// expected
}
r3.close();
dir.close();
}
public void testDeletes() throws Throwable {
Directory dir = newDirectory();
createIndex(random, dir, false); // Create an index with a bunch of docs (1 segment)
modifyIndex(0, dir); // Get delete bitVector on 1st segment
modifyIndex(5, dir); // Add a doc (2 segments)
IndexReader r1 = IndexReader.open(dir, false); // MSR
modifyIndex(5, dir); // Add another doc (3 segments)
IndexReader r2 = r1.reopen(); // MSR
assertTrue(r1 != r2);
SegmentReader sr1 = (SegmentReader) r1.getSequentialSubReaders()[0]; // Get SRs for the first segment from original
SegmentReader sr2 = (SegmentReader) r2.getSequentialSubReaders()[0]; // and reopened IRs
// At this point they share the same BitVector
assertTrue(sr1.deletedDocs==sr2.deletedDocs);
r2.deleteDocument(0);
// r1 should not see the delete
final Bits r1DelDocs = MultiFields.getDeletedDocs(r1);
assertFalse(r1DelDocs != null && r1DelDocs.get(0));
// Now r2 should have made a private copy of deleted docs:
assertTrue(sr1.deletedDocs!=sr2.deletedDocs);
r1.close();
r2.close();
dir.close();
}
public void testDeletes2() throws Throwable {
Directory dir = newDirectory();
createIndex(random, dir, false);
// Get delete bitVector
modifyIndex(0, dir);
IndexReader r1 = IndexReader.open(dir, false);
// Add doc:
modifyIndex(5, dir);
IndexReader r2 = r1.reopen();
assertTrue(r1 != r2);
IndexReader[] rs2 = r2.getSequentialSubReaders();
SegmentReader sr1 = getOnlySegmentReader(r1);
SegmentReader sr2 = (SegmentReader) rs2[0];
// At this point they share the same BitVector
assertTrue(sr1.deletedDocs==sr2.deletedDocs);
final BitVector delDocs = sr1.deletedDocs;
r1.close();
r2.deleteDocument(0);
assertTrue(delDocs==sr2.deletedDocs);
r2.close();
dir.close();
}
private static class KeepAllCommits implements IndexDeletionPolicy {
public void onInit(List<? extends IndexCommit> commits) {
}
public void onCommit(List<? extends IndexCommit> commits) {
}
}
public void testReopenOnCommit() throws Throwable {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
setIndexDeletionPolicy(new KeepAllCommits()).
setMaxBufferedDocs(-1).
setMergePolicy(newLogMergePolicy(10))
);
for(int i=0;i<4;i++) {
Document doc = new Document();
doc.add(newField("id", ""+i, Field.Store.NO, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
Map<String,String> data = new HashMap<String,String>();
data.put("index", i+"");
writer.commit(data);
}
for(int i=0;i<4;i++) {
writer.deleteDocuments(new Term("id", ""+i));
Map<String,String> data = new HashMap<String,String>();
data.put("index", (4+i)+"");
writer.commit(data);
}
writer.close();
IndexReader r = IndexReader.open(dir, false);
assertEquals(0, r.numDocs());
Collection<IndexCommit> commits = IndexReader.listCommits(dir);
for (final IndexCommit commit : commits) {
IndexReader r2 = r.reopen(commit);
assertTrue(r2 != r);
// Reader should be readOnly
try {
r2.deleteDocument(0);
fail("no exception hit");
} catch (UnsupportedOperationException uoe) {
// expected
}
final Map<String,String> s = commit.getUserData();
final int v;
if (s.size() == 0) {
// First commit created by IW
v = -1;
} else {
v = Integer.parseInt(s.get("index"));
}
if (v < 4) {
assertEquals(1+v, r2.numDocs());
} else {
assertEquals(7-v, r2.numDocs());
}
r.close();
r = r2;
}
r.close();
dir.close();
}
// LUCENE-1579: Make sure all SegmentReaders are new when
// reopen switches readOnly
public void testReopenChangeReadonly() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
setMaxBufferedDocs(-1).
setMergePolicy(newLogMergePolicy(10))
);
Document doc = new Document();
doc.add(newField("number", "17", Field.Store.NO, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
writer.commit();
// Open reader1
IndexReader r = IndexReader.open(dir, false);
assertTrue(r instanceof DirectoryReader);
IndexReader r1 = getOnlySegmentReader(r);
final int[] ints = FieldCache.DEFAULT.getInts(r1, "number");
assertEquals(1, ints.length);
assertEquals(17, ints[0]);
// Reopen to readonly w/ no chnages
IndexReader r3 = r.reopen(true);
assertTrue(((DirectoryReader) r3).readOnly);
r3.close();
// Add new segment
writer.addDocument(doc);
writer.commit();
// Reopen reader1 --> reader2
IndexReader r2 = r.reopen(true);
r.close();
assertTrue(((DirectoryReader) r2).readOnly);
IndexReader[] subs = r2.getSequentialSubReaders();
final int[] ints2 = FieldCache.DEFAULT.getInts(subs[0], "number");
r2.close();
assertTrue(((SegmentReader) subs[0]).readOnly);
assertTrue(((SegmentReader) subs[1]).readOnly);
assertTrue(ints == ints2);
writer.close();
dir.close();
}
}
| true | true | public void testThreadSafety() throws Exception {
final Directory dir = newDirectory();
final int n = atLeast(30);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
for (int i = 0; i < n; i++) {
writer.addDocument(createDocument(i, 3));
}
writer.optimize();
writer.close();
final TestReopen test = new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
if (i % 3 == 0) {
IndexReader modifier = IndexReader.open(dir, false);
Similarity sim = new DefaultSimilarity();
modifier.setNorm(i, "field1", sim.encodeNormValue(50f));
modifier.close();
} else if (i % 3 == 1) {
IndexReader modifier = IndexReader.open(dir, false);
modifier.deleteDocument(i % modifier.maxDoc());
modifier.close();
} else {
IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
modifier.addDocument(createDocument(n + i, 6));
modifier.close();
}
}
@Override
protected IndexReader openReader() throws IOException {
return IndexReader.open(dir, false);
}
};
final List<ReaderCouple> readers = Collections.synchronizedList(new ArrayList<ReaderCouple>());
IndexReader firstReader = IndexReader.open(dir, false);
IndexReader reader = firstReader;
final Random rnd = random;
ReaderThread[] threads = new ReaderThread[n];
final Set<IndexReader> readersToClose = Collections.synchronizedSet(new HashSet<IndexReader>());
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
IndexReader refreshed = reader.reopen();
if (refreshed != reader) {
readersToClose.add(reader);
}
reader = refreshed;
}
final IndexReader r = reader;
final int index = i;
ReaderThreadTask task;
if (i < 4 || (i >=10 && i < 14) || i > 18) {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
if (index % 2 == 0) {
// refresh reader synchronized
ReaderCouple c = (refreshReader(r, test, index, true));
readersToClose.add(c.newReader);
readersToClose.add(c.refreshedReader);
readers.add(c);
// prevent too many readers
break;
} else {
// not synchronized
IndexReader refreshed = r.reopen();
IndexSearcher searcher = newSearcher(refreshed);
ScoreDoc[] hits = searcher.search(
new TermQuery(new Term("field1", "a" + rnd.nextInt(refreshed.maxDoc()))),
null, 1000).scoreDocs;
if (hits.length > 0) {
searcher.doc(hits[0].doc);
}
searcher.close();
if (refreshed != r) {
refreshed.close();
}
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
} else {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
int numReaders = readers.size();
if (numReaders > 0) {
ReaderCouple c = readers.get(rnd.nextInt(numReaders));
TestIndexReader.assertIndexEquals(c.newReader, c.refreshedReader);
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
}
threads[i] = new ReaderThread(task);
threads[i].start();
}
synchronized(this) {
wait(1000);
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].stopThread();
}
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].join();
if (threads[i].error != null) {
String msg = "Error occurred in thread " + threads[i].getName() + ":\n" + threads[i].error.getMessage();
fail(msg);
}
}
}
for (final IndexReader readerToClose : readersToClose) {
readerToClose.close();
}
firstReader.close();
reader.close();
for (final IndexReader readerToClose : readersToClose) {
assertReaderClosed(readerToClose, true, true);
}
assertReaderClosed(reader, true, true);
assertReaderClosed(firstReader, true, true);
dir.close();
}
| public void testThreadSafety() throws Exception {
final Directory dir = newDirectory();
// NOTE: this also controls the number of threads!
final int n = _TestUtil.nextInt(random, 20, 40);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
for (int i = 0; i < n; i++) {
writer.addDocument(createDocument(i, 3));
}
writer.optimize();
writer.close();
final TestReopen test = new TestReopen() {
@Override
protected void modifyIndex(int i) throws IOException {
if (i % 3 == 0) {
IndexReader modifier = IndexReader.open(dir, false);
Similarity sim = new DefaultSimilarity();
modifier.setNorm(i, "field1", sim.encodeNormValue(50f));
modifier.close();
} else if (i % 3 == 1) {
IndexReader modifier = IndexReader.open(dir, false);
modifier.deleteDocument(i % modifier.maxDoc());
modifier.close();
} else {
IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random)));
modifier.addDocument(createDocument(n + i, 6));
modifier.close();
}
}
@Override
protected IndexReader openReader() throws IOException {
return IndexReader.open(dir, false);
}
};
final List<ReaderCouple> readers = Collections.synchronizedList(new ArrayList<ReaderCouple>());
IndexReader firstReader = IndexReader.open(dir, false);
IndexReader reader = firstReader;
final Random rnd = random;
ReaderThread[] threads = new ReaderThread[n];
final Set<IndexReader> readersToClose = Collections.synchronizedSet(new HashSet<IndexReader>());
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
IndexReader refreshed = reader.reopen();
if (refreshed != reader) {
readersToClose.add(reader);
}
reader = refreshed;
}
final IndexReader r = reader;
final int index = i;
ReaderThreadTask task;
if (i < 4 || (i >=10 && i < 14) || i > 18) {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
if (index % 2 == 0) {
// refresh reader synchronized
ReaderCouple c = (refreshReader(r, test, index, true));
readersToClose.add(c.newReader);
readersToClose.add(c.refreshedReader);
readers.add(c);
// prevent too many readers
break;
} else {
// not synchronized
IndexReader refreshed = r.reopen();
IndexSearcher searcher = newSearcher(refreshed);
ScoreDoc[] hits = searcher.search(
new TermQuery(new Term("field1", "a" + rnd.nextInt(refreshed.maxDoc()))),
null, 1000).scoreDocs;
if (hits.length > 0) {
searcher.doc(hits[0].doc);
}
searcher.close();
if (refreshed != r) {
refreshed.close();
}
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
} else {
task = new ReaderThreadTask() {
@Override
public void run() throws Exception {
while (!stopped) {
int numReaders = readers.size();
if (numReaders > 0) {
ReaderCouple c = readers.get(rnd.nextInt(numReaders));
TestIndexReader.assertIndexEquals(c.newReader, c.refreshedReader);
}
synchronized(this) {
wait(_TestUtil.nextInt(random, 1, 100));
}
}
}
};
}
threads[i] = new ReaderThread(task);
threads[i].start();
}
synchronized(this) {
wait(1000);
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].stopThread();
}
}
for (int i = 0; i < n; i++) {
if (threads[i] != null) {
threads[i].join();
if (threads[i].error != null) {
String msg = "Error occurred in thread " + threads[i].getName() + ":\n" + threads[i].error.getMessage();
fail(msg);
}
}
}
for (final IndexReader readerToClose : readersToClose) {
readerToClose.close();
}
firstReader.close();
reader.close();
for (final IndexReader readerToClose : readersToClose) {
assertReaderClosed(readerToClose, true, true);
}
assertReaderClosed(reader, true, true);
assertReaderClosed(firstReader, true, true);
dir.close();
}
|
diff --git a/src/test/ed/lang/python/PythonReloadTest.java b/src/test/ed/lang/python/PythonReloadTest.java
index ce2fee576..5ae475d27 100644
--- a/src/test/ed/lang/python/PythonReloadTest.java
+++ b/src/test/ed/lang/python/PythonReloadTest.java
@@ -1,327 +1,327 @@
package ed.lang.python;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.python.core.*;
import org.python.util.*;
import ed.js.Encoding;
import ed.appserver.JSFileLibrary;
import ed.appserver.AppContext;
import ed.appserver.AppRequest;
import ed.net.httpserver.HttpRequest;
import ed.appserver.templates.djang10.Printer.RedirectedPrinter;
import ed.js.JSLocalFile;
import ed.js.JSObjectBase;
import ed.js.JSString;
import ed.js.engine.Scope;
import ed.js.func.JSFunctionCalls1;
import ed.log.Level;
import ed.log.Logger;
import ed.lang.python.Python;
public class PythonReloadTest extends PythonTestCase {
private static final String TEST_DIR = "/tmp/pyreload";
private static final String TEST_DIR_SUB = "/tmp/pyreload/mymodule";
private static final File testDir = new File(TEST_DIR);
private static final File testDirSub = new File(TEST_DIR_SUB);
//time to wait between file modifications to allow the fs to update the timestamps
private static final long SLEEP_MS = 2000;
@BeforeClass
public void setUp() throws IOException, InterruptedException {
super.setUp(testDir);
super.setUp(testDirSub);
// Mark as a module
new File(testDirSub, "__init__.py").createNewFile();
}
@Test
public void test() throws IOException, InterruptedException {
Scope globalScope = initScope(testDir, "python-reload-test");
JSFileLibrary fileLib = (JSFileLibrary)globalScope.get("local");
writeTest1File1();
writeTest1File2();
writeTest1File3();
Scope oldScope = Scope.getThreadLocal();
globalScope.makeThreadLocal();
try {
globalScope.eval("local.file1();");
assertRan3(globalScope);
Thread.sleep(SLEEP_MS);
writeTest1File2();
PyObject m = Py.getSystemState().__findattr__("modules");
- shouldRun3(globalScope);
+ shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File3();
shouldRun3(globalScope);
Thread.sleep(SLEEP_MS);
// Test 4
writeTest4File1();
writeTest4File2();
writeTest4File3();
// 1 exec() 2 import 3
// 1 runs, execs 2 (runs unconditionally), imports 3 (runs once)
shouldRun3(globalScope);
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File1();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File3();
shouldRun3(globalScope);
// Test 5 -- __import__(file, {}) is tracked
Thread.sleep(SLEEP_MS);
writeTest5File1();
writeTest5File2();
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File2();
- shouldRun3(globalScope);
+ shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
// Test 6 -- importing in modules is tracked
globalScope = initScope(testDir, "python-reload-test6"); // flush sys.modules
globalScope.makeThreadLocal();
writeTest6File1();
writeTest6File2();
writeTest6File3();
writeTest6File4();
shouldRun3(globalScope);
// make sure right module was getting run
assertEquals(globalScope.get("ranSubFile3"), 100);
assertEquals(globalScope.get("ranModule"), 1);
globalScope.set("ranSubFile3", 0);
globalScope.set("ranModule", 0);
shouldRun1(globalScope);
assertEquals(globalScope.get("ranSubFile3"), 0);
assertEquals(globalScope.get("ranModule"), 0);
Thread.sleep(SLEEP_MS);
writeTest6File2();
- shouldRun3(globalScope);
+ shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest6File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
writeTest6File4();
shouldRun3(globalScope);
new File(testDirSub, "file3.py").delete();
new File(testDirSub, "file3$py.class").delete();
boolean reload = false;
try {
globalScope.eval("local.file1();");
}
catch(Exception e){
// Great -- module's gone, couldn't re-import, threw exception
reload = true;
}
assert reload;
}
finally {
if(oldScope != null)
oldScope.makeThreadLocal();
else
Scope.clearThreadLocal();
try {
rdelete(testDir);
} catch (Exception e) {
}
}
}
// file1 -> file2 -> file3
private void writeTest1File1() throws IOException{
fillFile(1, true);
}
private void writeTest1File2() throws IOException{
fillFile(2, true);
}
private void writeTest1File3() throws IOException{
fillFile(3, false);
}
private void fillFile(int n, boolean importNext) throws IOException{
fillFile(testDir, n, importNext);
}
private void fillFile(File dir, int n, boolean importNext) throws IOException{
File f = new File(dir, "file"+n+".py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile"+n+" = 1");
setTime(writer, "startFile1");
if(importNext)
writer.println("import file"+(n+1));
setTime(writer, "endFile1");
writer.close();
}
private void writeTest2File2() throws IOException{
File f = new File(testDir, "file2.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile2 = 1");
writer.println("import file2");
writer.close();
}
private void writeTest3File2() throws IOException{
fillFile(2, true);
}
private void writeTest3File3() throws IOException{
File f = new File(testDir, "file3.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile3 = 1");
writer.println("import file2");
writer.close();
}
private void writeTest4File1() throws IOException {
File f = new File(testDir, "file1.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile1 = 1");
writer.println("execfile('"+testDir+"/file2.py', {})");
writer.close();
}
private void writeTest4File2() throws IOException {
File f = new File(testDir, "file2.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile2 = 1");
writer.println("import file3");
writer.close();
}
private void writeTest4File3() throws IOException {
fillFile(3, false);
}
private void writeTest5File1() throws IOException {
fillFile(1, true);
}
private void writeTest5File2() throws IOException {
File f = new File(testDir, "file2.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile2 = 1");
writer.println("__import__('file3', {})");
writer.close();
}
private void writeTest5File3() throws IOException {
fillFile(3, false);
}
private void writeTest6File1() throws IOException {
fillFile(1, true);
}
private void writeTest6File2() throws IOException {
File f = new File(testDir, "file2.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile2 = 1");
writer.println("import mymodule.file3");
writer.println("assert mymodule.file3.someConstant == 4");
writer.close();
}
private void writeTest6File3() throws IOException {
File f = new File(testDirSub, "file3.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranFile3 = 1");
writer.println("_10gen.ranSubFile3 = 100");
writer.println("someConstant = 4");
writer.close();
}
private void writeTest6File4() throws IOException {
File f = new File(testDirSub, "__init__.py");
PrintWriter writer = new PrintWriter(f);
writer.println("import _10gen");
writer.println("_10gen.ranModule = 1");
writer.close();
}
public static void main(String [] args){
(new PythonReloadTest()).runConsole();
}
}
| false | true | public void test() throws IOException, InterruptedException {
Scope globalScope = initScope(testDir, "python-reload-test");
JSFileLibrary fileLib = (JSFileLibrary)globalScope.get("local");
writeTest1File1();
writeTest1File2();
writeTest1File3();
Scope oldScope = Scope.getThreadLocal();
globalScope.makeThreadLocal();
try {
globalScope.eval("local.file1();");
assertRan3(globalScope);
Thread.sleep(SLEEP_MS);
writeTest1File2();
PyObject m = Py.getSystemState().__findattr__("modules");
shouldRun3(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File3();
shouldRun3(globalScope);
Thread.sleep(SLEEP_MS);
// Test 4
writeTest4File1();
writeTest4File2();
writeTest4File3();
// 1 exec() 2 import 3
// 1 runs, execs 2 (runs unconditionally), imports 3 (runs once)
shouldRun3(globalScope);
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File1();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File3();
shouldRun3(globalScope);
// Test 5 -- __import__(file, {}) is tracked
Thread.sleep(SLEEP_MS);
writeTest5File1();
writeTest5File2();
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File2();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
// Test 6 -- importing in modules is tracked
globalScope = initScope(testDir, "python-reload-test6"); // flush sys.modules
globalScope.makeThreadLocal();
writeTest6File1();
writeTest6File2();
writeTest6File3();
writeTest6File4();
shouldRun3(globalScope);
// make sure right module was getting run
assertEquals(globalScope.get("ranSubFile3"), 100);
assertEquals(globalScope.get("ranModule"), 1);
globalScope.set("ranSubFile3", 0);
globalScope.set("ranModule", 0);
shouldRun1(globalScope);
assertEquals(globalScope.get("ranSubFile3"), 0);
assertEquals(globalScope.get("ranModule"), 0);
Thread.sleep(SLEEP_MS);
writeTest6File2();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest6File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
writeTest6File4();
shouldRun3(globalScope);
new File(testDirSub, "file3.py").delete();
new File(testDirSub, "file3$py.class").delete();
boolean reload = false;
try {
globalScope.eval("local.file1();");
}
catch(Exception e){
// Great -- module's gone, couldn't re-import, threw exception
reload = true;
}
assert reload;
}
finally {
if(oldScope != null)
oldScope.makeThreadLocal();
else
Scope.clearThreadLocal();
try {
rdelete(testDir);
} catch (Exception e) {
}
}
}
| public void test() throws IOException, InterruptedException {
Scope globalScope = initScope(testDir, "python-reload-test");
JSFileLibrary fileLib = (JSFileLibrary)globalScope.get("local");
writeTest1File1();
writeTest1File2();
writeTest1File3();
Scope oldScope = Scope.getThreadLocal();
globalScope.makeThreadLocal();
try {
globalScope.eval("local.file1();");
assertRan3(globalScope);
Thread.sleep(SLEEP_MS);
writeTest1File2();
PyObject m = Py.getSystemState().__findattr__("modules");
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest2File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File2();
writeTest3File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest3File3();
shouldRun3(globalScope);
Thread.sleep(SLEEP_MS);
// Test 4
writeTest4File1();
writeTest4File2();
writeTest4File3();
// 1 exec() 2 import 3
// 1 runs, execs 2 (runs unconditionally), imports 3 (runs once)
shouldRun3(globalScope);
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File1();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File2();
shouldRun2(globalScope);
Thread.sleep(SLEEP_MS);
writeTest4File3();
shouldRun3(globalScope);
// Test 5 -- __import__(file, {}) is tracked
Thread.sleep(SLEEP_MS);
writeTest5File1();
writeTest5File2();
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File2();
shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest5File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
// Test 6 -- importing in modules is tracked
globalScope = initScope(testDir, "python-reload-test6"); // flush sys.modules
globalScope.makeThreadLocal();
writeTest6File1();
writeTest6File2();
writeTest6File3();
writeTest6File4();
shouldRun3(globalScope);
// make sure right module was getting run
assertEquals(globalScope.get("ranSubFile3"), 100);
assertEquals(globalScope.get("ranModule"), 1);
globalScope.set("ranSubFile3", 0);
globalScope.set("ranModule", 0);
shouldRun1(globalScope);
assertEquals(globalScope.get("ranSubFile3"), 0);
assertEquals(globalScope.get("ranModule"), 0);
Thread.sleep(SLEEP_MS);
writeTest6File2();
shouldRun2(globalScope);
shouldRun1(globalScope);
Thread.sleep(SLEEP_MS);
writeTest6File3();
shouldRun3(globalScope);
shouldRun1(globalScope);
writeTest6File4();
shouldRun3(globalScope);
new File(testDirSub, "file3.py").delete();
new File(testDirSub, "file3$py.class").delete();
boolean reload = false;
try {
globalScope.eval("local.file1();");
}
catch(Exception e){
// Great -- module's gone, couldn't re-import, threw exception
reload = true;
}
assert reload;
}
finally {
if(oldScope != null)
oldScope.makeThreadLocal();
else
Scope.clearThreadLocal();
try {
rdelete(testDir);
} catch (Exception e) {
}
}
}
|
diff --git a/src/com/novell/spsample/client/AuthPanel.java b/src/com/novell/spsample/client/AuthPanel.java
index bb79d1fc..5ac6324f 100644
--- a/src/com/novell/spsample/client/AuthPanel.java
+++ b/src/com/novell/spsample/client/AuthPanel.java
@@ -1,110 +1,110 @@
/*
* Copyright (c) 2010 Unpublished Work of Novell, Inc. All Rights Reserved.
*
* THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL,
* PROPRIETARY AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS TO
* THIS WORK IS RESTRICTED TO (I) NOVELL, INC. EMPLOYEES WHO HAVE A NEED
* TO KNOW HOW TO PERFORM TASKS WITHIN THE SCOPE OF THEIR ASSIGNMENTS AND
* (II) ENTITIES OTHER THAN NOVELL, INC. WHO HAVE ENTERED INTO
* APPROPRIATE LICENSE AGREEMENTS. NO PART OF THIS WORK MAY BE USED,
* PRACTICED, PERFORMED, COPIED, DISTRIBUTED, REVISED, MODIFIED,
* TRANSLATED, ABRIDGED, CONDENSED, EXPANDED, COLLECTED, COMPILED,
* LINKED, RECAST, TRANSFORMED OR ADAPTED WITHOUT THE PRIOR WRITTEN
* CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION OF THIS WORK WITHOUT
* AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL
* LIABILITY.
*
* ========================================================================
*/
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.rest.RESTException;
import com.novell.spiffyui.client.rest.RESTObjectCallBack;
import com.novell.spsample.client.rest.SampleAuthBean;
/**
* This is the authentication documentation panel
*
*/
public class AuthPanel extends HTMLPanel
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private static AuthPanel g_authPanel;
/**
* Creates a new panel
*/
public AuthPanel()
{
super("div", STRINGS.AuthPanel_html());
getElement().setId("authPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
- final FancyTestButton authTestButton = new FancyTestButton("Login and Get Data Some Data");
+ final FancyTestButton authTestButton = new FancyTestButton("Login and Get Some Data");
authTestButton.getElement().setId("authTestBtn");
this.add(authTestButton, "testAuth");
authTestButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
authTestButton.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
authTestButton.setInProgress(false);
}
};
t.schedule(2000);
getData();
}
});
g_authPanel = this;
}
private void getData()
{
SampleAuthBean.getSampleAuthData(new RESTObjectCallBack<SampleAuthBean>() {
public void success(SampleAuthBean info)
{
String data = "You've logged in as " + info.getName() +
//" on " + DateTimeFormat.getFullDateFormat().format(info.getDate()) +
" and " + info.getMessage();
g_authPanel.add(new HTML(data), "testAuthResult");
/*
Add a yellow highlight to show that you've logged in
*/
RootPanel.get("loginSection").getElement().addClassName("yellowHighlightSection");
}
public void error(String message)
{
MessageUtil.showFatalError(message);
}
public void error(RESTException e)
{
MessageUtil.showFatalError(e.getReason());
}
});
}
}
| true | true | public AuthPanel()
{
super("div", STRINGS.AuthPanel_html());
getElement().setId("authPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
final FancyTestButton authTestButton = new FancyTestButton("Login and Get Data Some Data");
authTestButton.getElement().setId("authTestBtn");
this.add(authTestButton, "testAuth");
authTestButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
authTestButton.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
authTestButton.setInProgress(false);
}
};
t.schedule(2000);
getData();
}
});
g_authPanel = this;
}
| public AuthPanel()
{
super("div", STRINGS.AuthPanel_html());
getElement().setId("authPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
final FancyTestButton authTestButton = new FancyTestButton("Login and Get Some Data");
authTestButton.getElement().setId("authTestBtn");
this.add(authTestButton, "testAuth");
authTestButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
authTestButton.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
authTestButton.setInProgress(false);
}
};
t.schedule(2000);
getData();
}
});
g_authPanel = this;
}
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java b/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java
index 0c560f7..0f7572f 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java
@@ -1,2534 +1,2538 @@
/**
* Copyright (C) 2009-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.openstack.nova.os;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.openstack.nova.os.ext.hp.db.HPRDBMS;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class AbstractMethod {
protected NovaOpenStack provider;
public AbstractMethod(NovaOpenStack provider) { this.provider = provider; }
public synchronized @Nullable AuthenticationContext authenticate() throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticate()");
}
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("Unable to authenticate due to lack of context");
}
String endpoint = ctx.getEndpoint();
if( endpoint == null ) {
throw new CloudException("No authentication endpoint");
}
AuthenticationContext auth;
if( endpoint.startsWith("ks:") ) {
endpoint = endpoint.substring(3);
auth = authenticateKeystone(endpoint);
}
else if( endpoint.startsWith("st:") ) {
endpoint = endpoint.substring(3);
auth = authenticateStandard(endpoint);
}
else {
if( endpoint.endsWith("1.0") || endpoint.endsWith("1.0/") || endpoint.endsWith("1.1") || endpoint.endsWith("1.1/")) {
auth = authenticateStandard(endpoint);
if (auth == null) {
auth = authenticateSwift(endpoint);
}
if( auth == null ) {
auth = authenticateKeystone(endpoint);
}
}
else {
auth = authenticateKeystone(endpoint);
if( auth == null ) {
auth = authenticateStandard(endpoint);
}
if (auth == null) {
auth = authenticateSwift(endpoint);
}
}
}
return auth;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticate()");
}
}
}
private @Nullable AuthenticationContext authenticateKeystone(@Nonnull String endpoint) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticateKeystone(" + endpoint + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
wire.debug("");
}
try {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Attempting keystone authentication...");
}
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> credentials = new HashMap<String,Object>();
if( provider.getCloudProvider().equals(OpenStackProvider.HP ) ) {
if( std.isInfoEnabled() ) {
std.info("HP authentication");
}
try {
credentials.put("accessKey", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("secretKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("apiAccessKeyCredentials", credentials);
}
else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
if( std.isInfoEnabled() ) {
std.info("Rackspace authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("apiKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("RAX-KSKEY:apiKeyCredentials", credentials);
}
else {
if( std.isInfoEnabled() ) {
std.info("Standard authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("password", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("passwordCredentials", credentials);
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): tenantId=" + provider.getContext().getAccountNumber());
}
if( !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
String acct = provider.getContext().getAccountNumber();
if( provider.getCloudProvider().equals(OpenStackProvider.HP) ) {
json.put("tenantId", acct);
}
else {
// a hack
if( acct.length() == 32 ) {
json.put("tenantId", acct);
}
else {
json.put("tenantName", acct);
}
}
}
HashMap<String,Object> jsonAuth = new HashMap<String,Object>();
jsonAuth.put("auth", json);
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + "/tokens");
post.addHeader("Content-Type", "application/json");
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
String payload = (new JSONObject(jsonAuth)).toString();
try {
//noinspection deprecation
post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
try { wire.debug(EntityUtils.toString(post.getEntity())); }
catch( IOException ignore ) { }
wire.debug("");
HttpResponse response;
try {
APITrace.trace(provider, "POST authenticateKeystone");
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_OK ) {
if( code == 401 || code == 405 ) {
std.warn("authenticateKeystone(): Authentication failed");
return null;
}
std.error("authenticateKeystone(): Expected OK, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + "/tokens";
}
std.error("authenticateKeystone(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Keystone authentication successful");
}
String id, tenantId;
JSONArray catalog;
JSONObject token;
try {
JSONObject rj = new JSONObject(data);
JSONObject auth = rj.getJSONObject("access");
token = auth.getJSONObject("token");
catalog = auth.getJSONArray("serviceCatalog");
id = (token.has("id") ? token.getString("id") : null);
tenantId = ((token.has("tenantId") && !token.isNull("tenantId")) ? token.getString("tenantId") : null);
if( tenantId == null && token.has("tenant") && !token.isNull("tenant") ) {
JSONObject t = token.getJSONObject("tenant");
if( t.has("id") && !t.isNull("id") ) {
tenantId = t.getString("id");
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Invalid response from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( tenantId == null ) {
tenantId = provider.getContext().getAccountNumber();
}
if( id != null ) {
HashMap<String,Map<String,String>> services = new HashMap<String,Map<String,String>>();
HashMap<String,Map<String,String>> bestVersion = new HashMap<String,Map<String,String>>();
String myRegionId = provider.getContext().getRegionId();
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): myRegionId=" + myRegionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Processing service catalog...");
}
for( int i=0; i<catalog.length(); i++ ) {
try {
JSONObject service = catalog.getJSONObject(i);
/*
System.out.println("---------------------------------------------------");
System.out.println("Service=");
System.out.println(service.toString());
System.out.println("---------------------------------------------------");
*/
String type = service.getString("type");
JSONArray endpoints = service.getJSONArray("endpoints");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): type=" + type);
}
for( int j=0; j<endpoints.length(); j++ ) {
JSONObject test = endpoints.getJSONObject(j);
String url = test.getString("publicURL");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): endpoint[" + j + "]=" + url);
}
if( url != null ) {
String version = test.optString("versionId");
if( version == null || version.equals("") ) {
std.debug("No versionId parameter... Parsing URL " + url + " for best guess. (vSadTrombone)");
- Pattern p = Pattern.compile("/v(.+?)/|/v(.+?)$");
+ Pattern p = Pattern.compile("/volume/v(.+?)/|/v(.+?)/|/v(.+?)$");
Matcher m = p.matcher(url);
if (m.find()) {
version = m.group(1);
- if (version == null)
+ if (version == null) {
version = m.group(2);
+ if (version == null) {
+ version = m.group(3);
+ }
+ }
} else {
version = "1.0";
}
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): version[" + j + "]=" + version);
}
if( NovaOpenStack.isSupported(version) ) {
String regionId = (test.has("region") ? test.getString("region") : null);
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): region[" + j + "]=" + regionId);
}
Map<String,String> map = services.get(type);
Map<String,String> verMap = bestVersion.get(type);
if( map == null ) {
map = new HashMap<String,String>();
verMap = new HashMap<String,String>();
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+type+","+map+") into services.");
}
services.put(type, map);
bestVersion.put(type, verMap);
}
if( regionId == null & version.equals("1.0") && !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
std.warn("authenticateKeystone(): No region defined, making one up based on the URL: " + url);
regionId = toRegion(url);
std.warn("authenticateKeystone(): Fabricated region is: " + regionId);
}
else if( regionId == null && (type.equals("compute") || type.equals("object-store")) ) {
std.warn("authenticateKeystone(): No region defined for Rackspace, assuming it is pre-OpenStack and skipping");
continue;
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): finalRegionId=" + regionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Comparing " + version + " against " + verMap.get(type));
}
if (verMap.get(type) == null || compareVersions(version, verMap.get(type)) >= 0 ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+regionId+","+url+") into the "+type+" map.");
}
verMap.put(type, version);
map.put(regionId, url);
}
else {
std.warn("authenticateKeystone(): Skipping lower version url "+url+" for " + type+ " map.");
}
if( myRegionId == null ) {
myRegionId = regionId;
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): myRegionId now " + myRegionId);
}
}
}
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Failed to read JSON from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
}
if( std.isDebugEnabled() ) {
std.debug("services=" + services);
}
// TODO: remove this when HP has the DBaaS in the service catalog
if( provider.getCloudProvider().equals(OpenStackProvider.HP) && provider.getContext().getAccountNumber().equals("66565797737008") ) {
HashMap<String,String> endpoints = new HashMap<String, String>();
endpoints.put("region-a.geo-1", "https://region-a.geo-1.dbaas-mysql.hpcloudsvc.com:8779/v1.0/66565797737008");
services.put(HPRDBMS.SERVICE, endpoints);
}
return new AuthenticationContext(myRegionId, id, tenantId, services, null);
}
}
}
throw new CloudException("No authentication tokens were provided");
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticateKeystone()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
}
}
}
private @Nullable AuthenticationContext authenticateStandard(@Nonnull String endpointUrls) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticateStandard(" + endpointUrls + ")");
}
try {
String[] endpoints;
if( endpointUrls.indexOf(',') > 0 ) {
endpoints = endpointUrls.split(",");
}
else {
endpoints = new String[] { endpointUrls };
}
HashMap<String,Map<String,String>> services = new HashMap<String,Map<String,String>>();
String authToken = null, myRegion = provider.getContext().getRegionId();
String tenantId = provider.getContext().getAccountNumber();
for( String endpoint : endpoints ) {
if( wire.isDebugEnabled() ) {
wire.debug("STANDARD --------------------------------------------------------> " + endpoint);
wire.debug("");
}
try {
ProviderContext ctx = provider.getContext();
HttpClient client = getClient();
HttpGet get = new HttpGet(endpoint);
try {
get.addHeader("Content-Type", "application/json");
get.addHeader("X-Auth-User", new String(ctx.getAccessPublic(), "utf-8"));
get.addHeader("X-Auth-Key", new String(ctx.getAccessPrivate(), "utf-8"));
get.addHeader("X-Auth-Project-Id", ctx.getAccountNumber());
}
catch( UnsupportedEncodingException e ) {
std.error("authenticate(): Unsupported encoding when building request headers: " + e.getMessage());
if( std.isTraceEnabled() ) {
e.printStackTrace();
}
throw new InternalException(e);
}
if( wire.isDebugEnabled() ) {
wire.debug(get.getRequestLine().toString());
for( Header header : get.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "GET authenticateStandard");
response = client.execute(get);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_NO_CONTENT ) {
if( code == HttpStatus.SC_FORBIDDEN || code == HttpStatus.SC_UNAUTHORIZED ) {
return null;
}
std.error("authenticateStandard(): Expected NO CONTENT for an authentication request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( code == HttpStatus.SC_INTERNAL_SERVER_ERROR && data.contains("<faultstring>") ) {
return null;
}
if( wire.isDebugEnabled() ) {
wire.debug(response);
}
wire.debug("");
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items.type.equals(CloudErrorType.AUTHENTICATION) ) {
return null;
}
std.error("authenticateStandard(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
String cdnUrl = null, computeUrl = null, objectUrl = null;
String thisRegion = toRegion(endpoint);
if( myRegion == null ) {
myRegion = thisRegion;
}
for( Header h : response.getAllHeaders() ) {
if( h.getName().equalsIgnoreCase("x-auth-token") && myRegion.equals(thisRegion) ) {
authToken = h.getValue().trim();
}
else if( h.getName().equalsIgnoreCase("x-server-management-url") ) {
String url = h.getValue().trim();
if( url.endsWith("/") ) {
url = url.substring(0,url.length()-1);
}
if( endpoint.endsWith("v1.0") ) {
url = url + "/v1.0";
}
computeUrl = url;
}
else if( h.getName().equalsIgnoreCase("x-storage-url") ) {
objectUrl = h.getValue().trim();
}
else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) {
cdnUrl = h.getValue().trim();
}
}
if( computeUrl != null ) {
Map<String,String> map = services.get("compute");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, computeUrl);
}
services.put("compute", map);
}
if( objectUrl != null ) {
Map<String,String> map = services.get("object-store");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, objectUrl);
}
services.put("object-store", map);
}
if( cdnUrl != null ) {
Map<String,String> map = services.get("cdn");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, cdnUrl);
}
services.put("cdn", map);
}
}
}
finally {
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("STANDARD --------------------------------------------------------> " + endpoint);
}
}
}
if( authToken == null ) {
std.warn("authenticateStandard(): No authentication token in response");
throw new CloudException("No authentication token in cloud response");
}
return new AuthenticationContext(myRegion, authToken, tenantId, services, null);
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticateStandard()");
}
}
}
private @Nullable AuthenticationContext authenticateSwift(@Nonnull String endpoint) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticate()");
}
String tenantId = provider.getContext().getAccountNumber();
String authToken = null, storageToken = null;
String thisRegion = toRegion(endpoint);
if( wire.isDebugEnabled() ) {
wire.debug("--------------------------------------------------------> " + endpoint);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpGet get = new HttpGet(endpoint);
try {
ProviderContext ctx = provider.getContext();
String account;
if( ctx.getAccessPublic().length < 1 ) {
account = ctx.getAccountNumber();
}
else {
String pk = new String(ctx.getAccessPublic(), "utf-8");
if( pk.equals("-----") ) {
account = ctx.getAccountNumber();
}
else {
account = ctx.getAccountNumber() + ":" + new String(ctx.getAccessPublic(), "utf-8");
}
}
get.addHeader("Content-Type", "application/json");
get.addHeader("X-Auth-User", account);
get.addHeader("X-Auth-Key", new String(ctx.getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticate(): Unsupported encoding when building request headers: " + e.getMessage());
if( std.isTraceEnabled() ) {
e.printStackTrace();
}
throw new InternalException(e);
}
if( wire.isDebugEnabled() ) {
wire.debug(get.getRequestLine().toString());
for( Header header : get.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "GET authenticateSwift");
response = client.execute(get);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_OK ) {
if( code == HttpStatus.SC_FORBIDDEN || code == HttpStatus.SC_UNAUTHORIZED ) {
return null;
}
std.error("authenticate(): Expected NO CONTENT for an authentication request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items.type.equals(CloudErrorType.AUTHENTICATION) ) {
return null;
}
std.error("authenticate(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
HashMap<String,Map<String,String>> services = new HashMap<String,Map<String,String>>();
for( Header h : response.getAllHeaders() ) {
if( h.getName().equalsIgnoreCase("x-auth-token") ) {
authToken = h.getValue().trim();
}
else if( h.getName().equalsIgnoreCase("x-server-management-url") ) {
Map<String,String> map = services.get("compute");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, h.getValue().trim());
}
services.put("compute", map);
}
else if( h.getName().equalsIgnoreCase("x-storage-url") ) {
Map<String,String> map = services.get("object-store");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, h.getValue().trim());
}
services.put("object-store", map);
}
else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) {
Map<String,String> map = services.get("cdn");
if( map == null ) {
map = new HashMap<String,String>();
map.put(thisRegion, h.getValue().trim());
}
services.put("cdn", map);
}
else if( h.getName().equalsIgnoreCase("x-storage-token") ) {
storageToken = h.getValue().trim();
}
}
if( authToken == null ) {
std.warn("authenticate(): No authentication token in response");
throw new CloudException("No authentication token in cloud response");
}
return new AuthenticationContext(thisRegion, authToken, tenantId, services, storageToken);
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticate()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("--------------------------------------------------------> " + endpoint);
}
}
}
public void deleteResource(@Nonnull String service, @Nonnull String resource, @Nonnull String resourceId, String suffix) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " endpoint exists");
}
if( suffix == null ) {
resource = resource + "/" + resourceId;
}
else {
resource = resource + "/" + resourceId + "/" + suffix;
}
delete(context.getAuthToken(), endpoint, resource);
}
protected void delete(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".delete(" + authToken + "," + endpoint + "," + resource + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("--------------------------------------------------------> " + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpDelete delete = new HttpDelete(endpoint + resource);
delete.addHeader("Content-Type", "application/json");
delete.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(delete.getRequestLine().toString());
for( Header header : delete.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "DELETE " + toAPIResource(resource));
response = client.execute(delete);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_ACCEPTED ) {
std.error("delete(): Expected NO CONTENT for DELETE request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("delete(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
wire.debug("");
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".delete()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("--------------------------------------------------------> " + endpoint + resource);
}
}
}
public @Nullable JSONArray getList(@Nonnull String service, @Nonnull String resource, boolean suffix) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion());
}
if( suffix ) {
resource = resource + "/detail";
}
String response = getString(context.getAuthToken(), endpoint, resource);
if( response == null ) {
return null;
}
try {
return new JSONArray(response);
}
catch( JSONException e ) {
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response);
}
}
public @Nullable String[] getItemList(@Nonnull String service, @Nonnull String resource, boolean suffix) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion());
}
if( suffix ) {
resource = resource + "/detail";
}
String response = getString(context.getAuthToken(), endpoint, resource);
if( response == null ) {
return null;
}
if( response.length() < 1 ) {
return new String[0];
}
String[] items = response.split("\n");
if( items == null || items.length < 1 ) {
return new String[] { response.trim() };
}
for( int i=0; i< items.length; i++ ) {
items[i] = items[i].trim();
}
return items;
}
public @Nullable JSONObject getResource(@Nonnull String service, @Nonnull String resource, @Nullable String resourceId, boolean suffix) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion());
}
if( resourceId != null ) {
if( resourceId.startsWith("?") ) {
resource = resource + resourceId;
}
else {
resource = resource + "/" + resourceId;
}
}
else if( suffix ) {
resource = resource + "/detail";
}
String response = getString(context.getAuthToken(), endpoint, resource);
if( response == null ) {
return null;
}
try {
return new JSONObject(response);
}
catch( JSONException e ) {
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response);
}
}
protected @Nullable String getString(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".getString(" + authToken + "," + endpoint + "," + resource + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("--------------------------------------------------------> " + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpGet get = new HttpGet(resource == null ? endpoint : endpoint + resource);
get.addHeader("Content-Type", "application/json");
get.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(get.getRequestLine().toString());
for( Header header : get.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "GET " + toAPIResource(resource));
response = client.execute(get);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code == HttpStatus.SC_NOT_FOUND ) {
return null;
}
if( code == HttpStatus.SC_BAD_REQUEST ) {
std.error("Expected OK for GET request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
try {
JSONObject err = (new JSONObject(data)).getJSONObject("badRequest");
String msg = err.getString("message");
if( msg.contains("id should be integer") ) {
return null;
}
}
catch( JSONException e ) {
// ignore
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
return null;
}
if( provider.getMajorVersion() == 1 && provider.getMinorVersion() == 0 && items.message != null && (items.message.contains("not found") || items.message.contains("unknown")) ) {
return null;
}
std.error("getString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
if( code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_OK && code != HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION ) {
std.error("Expected OK for GET request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
return null;
}
if( provider.getMajorVersion() == 1 && provider.getMinorVersion() == 0 && items.message != null && (items.message.contains("not found") || items.message.contains("unknown")) ) {
return null;
}
std.error("getString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
std.info("Expected OK for GET request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
return data;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".getString()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("--------------------------------------------------------> " + endpoint + resource);
}
}
}
protected @Nullable InputStream getStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".getStream(" + authToken + "," + endpoint + "," + resource + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("--------------------------------------------------------> " + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpGet get = new HttpGet(endpoint + resource);
get.addHeader("Content-Type", "application/json");
get.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(get.getRequestLine().toString());
for( Header header : get.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "GET " + toAPIResource(resource));
response = client.execute(get);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code == HttpStatus.SC_NOT_FOUND ) {
return null;
}
if( code != HttpStatus.SC_OK && code != HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION ) {
std.error("Expected OK for GET request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
return null;
}
std.error("getStream(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
InputStream input = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
input = entity.getContent();
if( wire.isDebugEnabled() ) {
wire.debug(" ---- BINARY DATA ---- ");
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("getStream(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
if( std.isTraceEnabled() ) {
e.printStackTrace();
}
throw new CloudException(e);
}
if( wire.isDebugEnabled() ) {
wire.debug("---> Binary Data <---");
}
wire.debug("");
return input;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".getStream()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("--------------------------------------------------------> " + endpoint + resource);
}
}
}
protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was defined for this request");
}
String endpoint = ctx.getEndpoint();
if( endpoint == null ) {
throw new CloudException("No cloud endpoint was defined");
}
boolean ssl = endpoint.startsWith("https");
int targetPort;
URI uri;
try {
uri = new URI(endpoint);
targetPort = uri.getPort();
if( targetPort < 1 ) {
targetPort = (ssl ? 443 : 80);
}
}
catch( URISyntaxException e ) {
throw new CloudException(e);
}
HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//noinspection deprecation
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUserAgent(params, "");
Properties p = ctx.getCustomProperties();
if( p != null ) {
String proxyHost = p.getProperty("proxyHost");
String proxyPort = p.getProperty("proxyPort");
if( proxyHost != null ) {
int port = 0;
if( proxyPort != null && proxyPort.length() > 0 ) {
port = Integer.parseInt(proxyPort);
}
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http"));
}
}
DefaultHttpClient client = new DefaultHttpClient(params);
if( provider.isInsecure() ) {
try {
client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
}
catch( Throwable t ) {
t.printStackTrace();
}
}
return client;
}
public @Nullable Map<String,String> headResource(@Nonnull String service, @Nullable String resource, @Nullable String resourceId) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion());
}
if( resource == null && resourceId == null ) {
resource = "/";
}
else if( resource == null ) {
resource = "/" + resourceId;
}
else if( resourceId != null ) {
resource = resource + "/" + resourceId;
}
return head(context.getAuthToken(), endpoint, resource);
}
protected @Nullable Map<String,String> head(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".head(" + authToken + "," + endpoint + "," + resource + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("--------------------------------------------------------> " + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpHead head = new HttpHead(endpoint + resource);
head.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(head.getRequestLine().toString());
for( Header header : head.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "HEAD " + toAPIResource(resource));
response = client.execute(head);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_OK ) {
if( code == HttpStatus.SC_NOT_FOUND ) {
return null;
}
std.error("Expected OK for HEAD request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
return null;
}
std.error("head(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
HashMap<String,String> map = new HashMap<String,String>();
for( Header h : response.getAllHeaders() ) {
map.put(h.getName().trim(), h.getValue().trim());
}
return map;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".head()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("--------------------------------------------------------> " + endpoint + resource);
}
}
}
public void postResourceHeaders(String service, String resource, String resourceId, Map<String,String> headers) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " has been established in " + context.getMyRegion());
}
if( resourceId == null ) {
throw new InternalException("No container was specified");
}
postHeaders(context.getAuthToken(), endpoint, resource + "/" + resourceId, headers);
}
@SuppressWarnings("unused")
protected @Nullable String postHeaders(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull Map<String,String> customHeaders) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint + "," + resource + "," + customHeaders + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + resource);
post.addHeader("Content-Type", "application/json");
post.addHeader("X-Auth-Token", authToken);
if( customHeaders != null ) {
for( Map.Entry<String, String> entry : customHeaders.entrySet() ) {
String val = (entry.getValue() == null ? "" : entry.getValue());
post.addHeader(entry.getKey(), val);
}
}
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "POST " + toAPIResource(resource));
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code == HttpStatus.SC_REQUEST_TOO_LONG || code == HttpStatus.SC_REQUEST_URI_TOO_LONG ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
try {
if( data != null ) {
JSONObject ob = new JSONObject(data);
if( ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
if( ob.has("retryAfter") ) {
int min = ob.getInt("retryAfter");
try { Thread.sleep(CalendarWrapper.MINUTE * min); }
catch( InterruptedException ignore ) { }
return postHeaders(authToken, endpoint, resource, customHeaders);
}
}
}
}
catch( JSONException e ) {
throw new CloudException(e);
}
}
if( code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) {
std.error("postString(): Expected ACCEPTED for POST request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
if( code == HttpStatus.SC_ACCEPTED ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
public @Nullable JSONObject postString(@Nonnull String service, @Nonnull String resource, @Nullable String resourceId, @Nonnull String extra, @Nonnull JSONObject body) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " endpoint exists");
}
String response = postString(context.getAuthToken(), endpoint, resource + "/" + resourceId + "/" + extra, body.toString());
if( response == null ) {
return null;
}
try {
return new JSONObject(response);
}
catch( JSONException e ) {
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response);
}
}
public @Nullable JSONObject postString(@Nonnull String service, @Nonnull String resource, @Nullable String resourceId, @Nonnull JSONObject body, boolean suffix) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
if( resourceId != null ) {
resource = resource + "/" + (suffix ? (resourceId + "/action") : resourceId);
}
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " endpoint exists");
}
String response = postString(context.getAuthToken(), endpoint, resource, body.toString());
if( response == null ) {
return null;
}
try {
return new JSONObject(response);
}
catch( JSONException e ) {
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response);
}
}
protected @Nullable String postString(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull String payload) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint + "," + resource + "," + payload + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + resource);
post.addHeader("Content-Type", "application/json");
post.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
if( payload != null ) {
try {
//noinspection deprecation
post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
try { wire.debug(EntityUtils.toString(post.getEntity())); }
catch( IOException ignore ) { }
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "POST " + toAPIResource(resource));
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code == HttpStatus.SC_REQUEST_TOO_LONG || code == HttpStatus.SC_REQUEST_URI_TOO_LONG ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
try {
if( data != null ) {
JSONObject ob = new JSONObject(data);
if( ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
if( ob.has("retryAfter") ) {
int min = ob.getInt("retryAfter");
try { Thread.sleep(CalendarWrapper.MINUTE * min); }
catch( InterruptedException ignore ) { }
return postString(authToken, endpoint, resource, payload);
}
}
}
}
catch( JSONException e ) {
throw new CloudException(e);
}
}
if( code != HttpStatus.SC_OK && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_CREATED ) {
std.error("postString(): Expected OK, ACCEPTED, or NO CONTENT for POST request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
if( code != HttpStatus.SC_NO_CONTENT ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
else if( code == HttpStatus.SC_ACCEPTED ) {
Header[] headers = response.getAllHeaders();
for( Header h : headers ) {
if( h.getName().equalsIgnoreCase("Location") ) {
return "{\"location\" : \"" + h.getValue().trim() + "\"}";
}
}
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
@SuppressWarnings("unused")
protected @Nullable String postStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull String md5Hash, @Nonnull InputStream stream) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".postStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + resource);
post.addHeader("Content-Type", "application/octet-stream");
post.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
post.setEntity(new InputStreamEntity(stream, -1));
wire.debug(" ---- BINARY DATA ---- ");
wire.debug("");
HttpResponse response;
try {
APITrace.trace(provider, "POST " + toAPIResource(resource));
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
String responseHash = null;
for( Header h : post.getAllHeaders() ) {
if( h.getName().equalsIgnoreCase("ETag") ) {
responseHash = h.getValue();
}
}
if( responseHash != null && md5Hash != null && !responseHash.equals(md5Hash) ) {
throw new CloudException("MD5 hash values do not match, probably data corruption");
}
if( code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) {
std.error("postStream(): Expected ACCEPTED or NO CONTENT for POST request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
wire.debug("");
if( code == HttpStatus.SC_ACCEPTED ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + NovaOpenStack.class.getName() + ".postStream()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
public void putResourceHeaders(@Nonnull String service, @Nullable String resource, @Nullable String resourceId, @Nonnull Map<String,String> headers) throws CloudException, InternalException {
AuthenticationContext context = provider.getAuthenticationContext();
String endpoint = context.getServiceUrl(service);
if( endpoint == null ) {
throw new CloudException("No " + service + " has been established in " + context.getMyRegion());
}
if( resource == null && resourceId == null ) {
resource = "/";
}
else if( resource == null ) {
resource = "/" + resourceId;
}
else if( resourceId != null ) {
resource = resource + "/" + resourceId;
}
putHeaders(context.getAuthToken(), endpoint, resource, headers);
}
@SuppressWarnings("unused")
protected @Nonnull String putHeaders(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull Map<String,String> customHeaders) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".putHeaders(" + authToken + "," + endpoint + "," + resource + "," + customHeaders + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPut put = new HttpPut(endpoint + resource);
put.addHeader("Content-Type", "application/json");
put.addHeader("X-Auth-Token", authToken);
if( customHeaders != null ) {
for( Map.Entry<String, String> entry : customHeaders.entrySet() ) {
String val = (entry.getValue() == null ? "" : entry.getValue());
put.addHeader(entry.getKey(), val);
}
}
if( wire.isDebugEnabled() ) {
wire.debug(put.getRequestLine().toString());
for( Header header : put.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "PUT " + toAPIResource(resource));
response = client.execute(put);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) {
std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("putString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
if( code == HttpStatus.SC_ACCEPTED || code == HttpStatus.SC_CREATED ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".putString()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
protected @Nullable String putString(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".putString(" + authToken + "," + endpoint + "," + resource + "," + payload + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPut put = new HttpPut(endpoint + resource);
put.addHeader("Content-Type", "application/json");
put.addHeader("X-Auth-Token", authToken);
if( wire.isDebugEnabled() ) {
wire.debug(put.getRequestLine().toString());
for( Header header : put.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
if( payload != null ) {
try {
//noinspection deprecation
put.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
try { wire.debug(EntityUtils.toString(put.getEntity())); }
catch( IOException ignore ) { }
wire.debug("");
}
HttpResponse response;
try {
APITrace.trace(provider, "PUT " + toAPIResource(resource));
response = client.execute(put);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) {
std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("putString(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
if( code == HttpStatus.SC_ACCEPTED || code == HttpStatus.SC_CREATED ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".putString()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
protected @Nullable String putStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String md5Hash, @Nonnull InputStream stream) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".putStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)");
}
if( wire.isDebugEnabled() ) {
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
wire.debug("");
}
try {
HttpClient client = getClient();
HttpPut put = new HttpPut(endpoint + resource);
put.addHeader("Content-Type", "application/octet-stream");
put.addHeader("X-Auth-Token", authToken);
if( md5Hash != null ) {
put.addHeader("ETag", md5Hash);
}
if( wire.isDebugEnabled() ) {
wire.debug(put.getRequestLine().toString());
for( Header header : put.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
put.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM));
wire.debug(" ---- BINARY DATA ---- ");
wire.debug("");
HttpResponse response;
try {
APITrace.trace(provider, "PUT " + toAPIResource(resource));
response = client.execute(put);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
String responseHash = null;
for( Header h : put.getAllHeaders() ) {
if( h.getName().equalsIgnoreCase("ETag") ) {
responseHash = h.getValue();
}
}
if( responseHash != null && md5Hash != null && !responseHash.equals(md5Hash) ) {
throw new CloudException("MD5 hash values do not match, probably data corruption");
}
if( code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) {
std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + resource;
}
std.error("putStream(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
if( code == HttpStatus.SC_ACCEPTED ) {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
return data;
}
}
return null;
}
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + NovaOpenStack.class.getName() + ".putStream()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("---------------------------------------------------------------------------------" + endpoint + resource);
}
}
}
private @Nonnull String toRegion(@Nonnull String endpoint) {
Logger logger = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
if( logger.isTraceEnabled() ) {
logger.trace("enter - " + AbstractMethod.class.getName() + ".toRegion(" + endpoint + ")");
}
try {
if( logger.isInfoEnabled() ) {
logger.info("Looking up official region for " + endpoint);
}
String host;
try {
URI uri = new URI(endpoint);
host = uri.getHost();
}
catch( URISyntaxException e ) {
host = endpoint;
}
String[] parts = host.split("\\.");
String regionId;
if( parts.length < 3 ) {
regionId = host;
}
else if( parts.length == 3 ) {
regionId = parts[0];
}
else {
regionId = parts[0] + "." + parts[1];
}
if( logger.isDebugEnabled() ) {
logger.debug("regionId=" + regionId);
}
return regionId;
}
finally {
if( logger.isTraceEnabled() ) {
logger.trace("exit - " + AbstractMethod.class.getName() + ".toRegion()");
}
}
}
private @Nonnegative int compareVersions(@Nullable String ver1, @Nullable String ver2) throws InternalException {
Logger logger = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
if( logger.isTraceEnabled() ) {
logger.trace("enter - " + AbstractMethod.class.getName() + ".compareVersions("+ver1+","+ver2+")");
}
int result = 0;
if( ver1 == null && ver2 == null ) {
return 0;
}
else if( ver1 == null ) {
ver1 = "1.0";
}
else if( ver2 == null ) {
ver2 = "1.0";
}
//Assumes only x.x granularity. Anything more will require rewrite of this component.
try {
String majorStr1 = ver1.contains(".") ? ver1.substring(0,ver1.indexOf(".")) : ver1;
String minorStr1 = ver1.contains(".") ? ver1.substring(ver1.indexOf(".")+1) : "0";
String majorStr2 = ver2.contains(".") ? ver2.substring(0,ver2.indexOf(".")) : ver2;
String minorStr2 = ver2.contains(".") ? ver2.substring(ver2.indexOf(".")+1) : "0";
int major1 = Integer.parseInt(majorStr1);
int minor1 = Integer.parseInt(minorStr1);
int major2 = Integer.parseInt(majorStr2);
int minor2 = Integer.parseInt(minorStr2);
result = major1 - major2;
if (result==0)
result = minor1 - minor2;
} catch (Exception e) {
// Something really stupid showed up in the version string...
throw new InternalException(e);
}
finally {
if( logger.isTraceEnabled() ) {
logger.trace("exit - "+AbstractMethod.class.getName() + ".compareVersions("+ver1+","+ver2+") = "+result);
}
}
return result;
}
private @Nonnull String toAPIResource(@Nonnull String resource) {
if( resource == null || resource.equals("/") || resource.length() < 2 ) {
return resource;
}
while( resource.startsWith("/") ) {
if( resource.equals("/") ) {
return "/";
}
resource = resource.substring(1);
}
int idx = resource.indexOf("/");
if( idx > 0 ) {
return resource.substring(0, idx);
}
return resource;
}
}
| false | true | private @Nullable AuthenticationContext authenticateKeystone(@Nonnull String endpoint) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticateKeystone(" + endpoint + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
wire.debug("");
}
try {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Attempting keystone authentication...");
}
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> credentials = new HashMap<String,Object>();
if( provider.getCloudProvider().equals(OpenStackProvider.HP ) ) {
if( std.isInfoEnabled() ) {
std.info("HP authentication");
}
try {
credentials.put("accessKey", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("secretKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("apiAccessKeyCredentials", credentials);
}
else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
if( std.isInfoEnabled() ) {
std.info("Rackspace authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("apiKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("RAX-KSKEY:apiKeyCredentials", credentials);
}
else {
if( std.isInfoEnabled() ) {
std.info("Standard authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("password", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("passwordCredentials", credentials);
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): tenantId=" + provider.getContext().getAccountNumber());
}
if( !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
String acct = provider.getContext().getAccountNumber();
if( provider.getCloudProvider().equals(OpenStackProvider.HP) ) {
json.put("tenantId", acct);
}
else {
// a hack
if( acct.length() == 32 ) {
json.put("tenantId", acct);
}
else {
json.put("tenantName", acct);
}
}
}
HashMap<String,Object> jsonAuth = new HashMap<String,Object>();
jsonAuth.put("auth", json);
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + "/tokens");
post.addHeader("Content-Type", "application/json");
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
String payload = (new JSONObject(jsonAuth)).toString();
try {
//noinspection deprecation
post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
try { wire.debug(EntityUtils.toString(post.getEntity())); }
catch( IOException ignore ) { }
wire.debug("");
HttpResponse response;
try {
APITrace.trace(provider, "POST authenticateKeystone");
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_OK ) {
if( code == 401 || code == 405 ) {
std.warn("authenticateKeystone(): Authentication failed");
return null;
}
std.error("authenticateKeystone(): Expected OK, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + "/tokens";
}
std.error("authenticateKeystone(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Keystone authentication successful");
}
String id, tenantId;
JSONArray catalog;
JSONObject token;
try {
JSONObject rj = new JSONObject(data);
JSONObject auth = rj.getJSONObject("access");
token = auth.getJSONObject("token");
catalog = auth.getJSONArray("serviceCatalog");
id = (token.has("id") ? token.getString("id") : null);
tenantId = ((token.has("tenantId") && !token.isNull("tenantId")) ? token.getString("tenantId") : null);
if( tenantId == null && token.has("tenant") && !token.isNull("tenant") ) {
JSONObject t = token.getJSONObject("tenant");
if( t.has("id") && !t.isNull("id") ) {
tenantId = t.getString("id");
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Invalid response from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( tenantId == null ) {
tenantId = provider.getContext().getAccountNumber();
}
if( id != null ) {
HashMap<String,Map<String,String>> services = new HashMap<String,Map<String,String>>();
HashMap<String,Map<String,String>> bestVersion = new HashMap<String,Map<String,String>>();
String myRegionId = provider.getContext().getRegionId();
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): myRegionId=" + myRegionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Processing service catalog...");
}
for( int i=0; i<catalog.length(); i++ ) {
try {
JSONObject service = catalog.getJSONObject(i);
/*
System.out.println("---------------------------------------------------");
System.out.println("Service=");
System.out.println(service.toString());
System.out.println("---------------------------------------------------");
*/
String type = service.getString("type");
JSONArray endpoints = service.getJSONArray("endpoints");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): type=" + type);
}
for( int j=0; j<endpoints.length(); j++ ) {
JSONObject test = endpoints.getJSONObject(j);
String url = test.getString("publicURL");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): endpoint[" + j + "]=" + url);
}
if( url != null ) {
String version = test.optString("versionId");
if( version == null || version.equals("") ) {
std.debug("No versionId parameter... Parsing URL " + url + " for best guess. (vSadTrombone)");
Pattern p = Pattern.compile("/v(.+?)/|/v(.+?)$");
Matcher m = p.matcher(url);
if (m.find()) {
version = m.group(1);
if (version == null)
version = m.group(2);
} else {
version = "1.0";
}
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): version[" + j + "]=" + version);
}
if( NovaOpenStack.isSupported(version) ) {
String regionId = (test.has("region") ? test.getString("region") : null);
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): region[" + j + "]=" + regionId);
}
Map<String,String> map = services.get(type);
Map<String,String> verMap = bestVersion.get(type);
if( map == null ) {
map = new HashMap<String,String>();
verMap = new HashMap<String,String>();
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+type+","+map+") into services.");
}
services.put(type, map);
bestVersion.put(type, verMap);
}
if( regionId == null & version.equals("1.0") && !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
std.warn("authenticateKeystone(): No region defined, making one up based on the URL: " + url);
regionId = toRegion(url);
std.warn("authenticateKeystone(): Fabricated region is: " + regionId);
}
else if( regionId == null && (type.equals("compute") || type.equals("object-store")) ) {
std.warn("authenticateKeystone(): No region defined for Rackspace, assuming it is pre-OpenStack and skipping");
continue;
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): finalRegionId=" + regionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Comparing " + version + " against " + verMap.get(type));
}
if (verMap.get(type) == null || compareVersions(version, verMap.get(type)) >= 0 ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+regionId+","+url+") into the "+type+" map.");
}
verMap.put(type, version);
map.put(regionId, url);
}
else {
std.warn("authenticateKeystone(): Skipping lower version url "+url+" for " + type+ " map.");
}
if( myRegionId == null ) {
myRegionId = regionId;
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): myRegionId now " + myRegionId);
}
}
}
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Failed to read JSON from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
}
if( std.isDebugEnabled() ) {
std.debug("services=" + services);
}
// TODO: remove this when HP has the DBaaS in the service catalog
if( provider.getCloudProvider().equals(OpenStackProvider.HP) && provider.getContext().getAccountNumber().equals("66565797737008") ) {
HashMap<String,String> endpoints = new HashMap<String, String>();
endpoints.put("region-a.geo-1", "https://region-a.geo-1.dbaas-mysql.hpcloudsvc.com:8779/v1.0/66565797737008");
services.put(HPRDBMS.SERVICE, endpoints);
}
return new AuthenticationContext(myRegionId, id, tenantId, services, null);
}
}
}
throw new CloudException("No authentication tokens were provided");
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticateKeystone()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
}
}
}
| private @Nullable AuthenticationContext authenticateKeystone(@Nonnull String endpoint) throws CloudException, InternalException {
Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");
if( std.isTraceEnabled() ) {
std.trace("enter - " + AbstractMethod.class.getName() + ".authenticateKeystone(" + endpoint + ")");
}
if( wire.isDebugEnabled() ) {
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
wire.debug("");
}
try {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Attempting keystone authentication...");
}
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> credentials = new HashMap<String,Object>();
if( provider.getCloudProvider().equals(OpenStackProvider.HP ) ) {
if( std.isInfoEnabled() ) {
std.info("HP authentication");
}
try {
credentials.put("accessKey", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("secretKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("apiAccessKeyCredentials", credentials);
}
else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
if( std.isInfoEnabled() ) {
std.info("Rackspace authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("apiKey", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("RAX-KSKEY:apiKeyCredentials", credentials);
}
else {
if( std.isInfoEnabled() ) {
std.info("Standard authentication");
}
try {
credentials.put("username", new String(provider.getContext().getAccessPublic(), "utf-8"));
credentials.put("password", new String(provider.getContext().getAccessPrivate(), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
json.put("passwordCredentials", credentials);
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): tenantId=" + provider.getContext().getAccountNumber());
}
if( !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
String acct = provider.getContext().getAccountNumber();
if( provider.getCloudProvider().equals(OpenStackProvider.HP) ) {
json.put("tenantId", acct);
}
else {
// a hack
if( acct.length() == 32 ) {
json.put("tenantId", acct);
}
else {
json.put("tenantName", acct);
}
}
}
HashMap<String,Object> jsonAuth = new HashMap<String,Object>();
jsonAuth.put("auth", json);
HttpClient client = getClient();
HttpPost post = new HttpPost(endpoint + "/tokens");
post.addHeader("Content-Type", "application/json");
if( wire.isDebugEnabled() ) {
wire.debug(post.getRequestLine().toString());
for( Header header : post.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
String payload = (new JSONObject(jsonAuth)).toString();
try {
//noinspection deprecation
post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
try { wire.debug(EntityUtils.toString(post.getEntity())); }
catch( IOException ignore ) { }
wire.debug("");
HttpResponse response;
try {
APITrace.trace(provider, "POST authenticateKeystone");
response = client.execute(post);
if( wire.isDebugEnabled() ) {
wire.debug(response.getStatusLine().toString());
for( Header header : response.getAllHeaders() ) {
wire.debug(header.getName() + ": " + header.getValue());
}
wire.debug("");
}
}
catch( IOException e ) {
std.error("I/O error from server communications: " + e.getMessage());
e.printStackTrace();
throw new InternalException(e);
}
int code = response.getStatusLine().getStatusCode();
std.debug("HTTP STATUS: " + code);
if( code != HttpStatus.SC_OK ) {
if( code == 401 || code == 405 ) {
std.warn("authenticateKeystone(): Authentication failed");
return null;
}
std.error("authenticateKeystone(): Expected OK, got " + code);
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
NovaException.ExceptionItems items = NovaException.parseException(code, data);
if( items == null ) {
items = new NovaException.ExceptionItems();
items.code = 404;
items.type = CloudErrorType.COMMUNICATION;
items.message = "itemNotFound";
items.details = "No such object: " + "/tokens";
}
std.error("authenticateKeystone(): [" + code + " : " + items.message + "] " + items.details);
throw new NovaException(items);
}
else {
String data = null;
try {
HttpEntity entity = response.getEntity();
if( entity != null ) {
data = EntityUtils.toString(entity);
if( wire.isDebugEnabled() ) {
wire.debug(data);
wire.debug("");
}
}
}
catch( IOException e ) {
std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( data != null && !data.trim().equals("") ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Keystone authentication successful");
}
String id, tenantId;
JSONArray catalog;
JSONObject token;
try {
JSONObject rj = new JSONObject(data);
JSONObject auth = rj.getJSONObject("access");
token = auth.getJSONObject("token");
catalog = auth.getJSONArray("serviceCatalog");
id = (token.has("id") ? token.getString("id") : null);
tenantId = ((token.has("tenantId") && !token.isNull("tenantId")) ? token.getString("tenantId") : null);
if( tenantId == null && token.has("tenant") && !token.isNull("tenant") ) {
JSONObject t = token.getJSONObject("tenant");
if( t.has("id") && !t.isNull("id") ) {
tenantId = t.getString("id");
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Invalid response from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
if( tenantId == null ) {
tenantId = provider.getContext().getAccountNumber();
}
if( id != null ) {
HashMap<String,Map<String,String>> services = new HashMap<String,Map<String,String>>();
HashMap<String,Map<String,String>> bestVersion = new HashMap<String,Map<String,String>>();
String myRegionId = provider.getContext().getRegionId();
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): myRegionId=" + myRegionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Processing service catalog...");
}
for( int i=0; i<catalog.length(); i++ ) {
try {
JSONObject service = catalog.getJSONObject(i);
/*
System.out.println("---------------------------------------------------");
System.out.println("Service=");
System.out.println(service.toString());
System.out.println("---------------------------------------------------");
*/
String type = service.getString("type");
JSONArray endpoints = service.getJSONArray("endpoints");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): type=" + type);
}
for( int j=0; j<endpoints.length(); j++ ) {
JSONObject test = endpoints.getJSONObject(j);
String url = test.getString("publicURL");
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): endpoint[" + j + "]=" + url);
}
if( url != null ) {
String version = test.optString("versionId");
if( version == null || version.equals("") ) {
std.debug("No versionId parameter... Parsing URL " + url + " for best guess. (vSadTrombone)");
Pattern p = Pattern.compile("/volume/v(.+?)/|/v(.+?)/|/v(.+?)$");
Matcher m = p.matcher(url);
if (m.find()) {
version = m.group(1);
if (version == null) {
version = m.group(2);
if (version == null) {
version = m.group(3);
}
}
} else {
version = "1.0";
}
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): version[" + j + "]=" + version);
}
if( NovaOpenStack.isSupported(version) ) {
String regionId = (test.has("region") ? test.getString("region") : null);
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): region[" + j + "]=" + regionId);
}
Map<String,String> map = services.get(type);
Map<String,String> verMap = bestVersion.get(type);
if( map == null ) {
map = new HashMap<String,String>();
verMap = new HashMap<String,String>();
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+type+","+map+") into services.");
}
services.put(type, map);
bestVersion.put(type, verMap);
}
if( regionId == null & version.equals("1.0") && !provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) {
std.warn("authenticateKeystone(): No region defined, making one up based on the URL: " + url);
regionId = toRegion(url);
std.warn("authenticateKeystone(): Fabricated region is: " + regionId);
}
else if( regionId == null && (type.equals("compute") || type.equals("object-store")) ) {
std.warn("authenticateKeystone(): No region defined for Rackspace, assuming it is pre-OpenStack and skipping");
continue;
}
if( std.isDebugEnabled() ) {
std.debug("authenticateKeystone(): finalRegionId=" + regionId);
}
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Comparing " + version + " against " + verMap.get(type));
}
if (verMap.get(type) == null || compareVersions(version, verMap.get(type)) >= 0 ) {
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): Putting ("+regionId+","+url+") into the "+type+" map.");
}
verMap.put(type, version);
map.put(regionId, url);
}
else {
std.warn("authenticateKeystone(): Skipping lower version url "+url+" for " + type+ " map.");
}
if( myRegionId == null ) {
myRegionId = regionId;
if( std.isInfoEnabled() ) {
std.info("authenticateKeystone(): myRegionId now " + myRegionId);
}
}
}
}
}
}
catch( JSONException e ) {
std.error("authenticateKeystone(): Failed to read JSON from server: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
}
if( std.isDebugEnabled() ) {
std.debug("services=" + services);
}
// TODO: remove this when HP has the DBaaS in the service catalog
if( provider.getCloudProvider().equals(OpenStackProvider.HP) && provider.getContext().getAccountNumber().equals("66565797737008") ) {
HashMap<String,String> endpoints = new HashMap<String, String>();
endpoints.put("region-a.geo-1", "https://region-a.geo-1.dbaas-mysql.hpcloudsvc.com:8779/v1.0/66565797737008");
services.put(HPRDBMS.SERVICE, endpoints);
}
return new AuthenticationContext(myRegionId, id, tenantId, services, null);
}
}
}
throw new CloudException("No authentication tokens were provided");
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + AbstractMethod.class.getName() + ".authenticateKeystone()");
}
if( wire.isDebugEnabled() ) {
wire.debug("");
wire.debug("KEYSTONE --------------------------------------------------------> " + endpoint);
}
}
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-adt/org/eclipse/wst/xsd/ui/internal/adt/design/DesignViewGraphicalViewer.java b/bundles/org.eclipse.wst.xsd.ui/src-adt/org/eclipse/wst/xsd/ui/internal/adt/design/DesignViewGraphicalViewer.java
index cc6893516..b78ec43c9 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src-adt/org/eclipse/wst/xsd/ui/internal/adt/design/DesignViewGraphicalViewer.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src-adt/org/eclipse/wst/xsd/ui/internal/adt/design/DesignViewGraphicalViewer.java
@@ -1,275 +1,282 @@
/*******************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.xsd.ui.internal.adt.design;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.RootContentEditPart;
import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.model.IGraphElement;
import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.model.IModelProxy;
import org.eclipse.wst.xsd.ui.internal.adt.editor.CommonSelectionManager;
import org.eclipse.wst.xsd.ui.internal.adt.facade.IADTObject;
import org.eclipse.wst.xsd.ui.internal.adt.facade.IField;
import org.eclipse.wst.xsd.ui.internal.adt.facade.IModel;
import org.eclipse.wst.xsd.ui.internal.adt.facade.IStructure;
import org.eclipse.wst.xsd.ui.internal.adt.outline.ADTContentOutlinePage;
public class DesignViewGraphicalViewer extends ScrollingGraphicalViewer implements ISelectionChangedListener
{
protected ADTSelectionChangedListener internalSelectionProvider = new ADTSelectionChangedListener();
protected InputChangeManager inputChangeManager = new InputChangeManager();
public DesignViewGraphicalViewer(IEditorPart editor, CommonSelectionManager manager)
{
super();
setContextMenu(new DesignViewContextMenuProvider(editor, this, this));
editor.getEditorSite().registerContextMenu("org.eclipse.wst.xsd.ui.popup.graph", getContextMenu(), internalSelectionProvider, false); //$NON-NLS-1$
// make the internalSelectionProvider listen to graph view selection changes
addSelectionChangedListener(internalSelectionProvider);
internalSelectionProvider.addSelectionChangedListener(manager);
manager.addSelectionChangedListener(this);
}
// this method is called when something changes in the selection manager
// (e.g. a selection occured from another view)
public void selectionChanged(SelectionChangedEvent event)
{
Object selectedObject = ((StructuredSelection) event.getSelection()).getFirstElement();
// TODO (cs) It seems like there's way more selection going on than there
// should
// be!! There's at least 2 selections getting fired when something is
// selected in the
// outline view. Are we listening to too many things?
//
// if (event.getSource() instanceof ADTContentOutlinePage)
if (event.getSource() != internalSelectionProvider)
{
if (selectedObject instanceof IStructure)
{
if (((getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
(!(getInput() instanceof IModel)))
{
if (selectedObject instanceof IGraphElement)
{
if (((IGraphElement)selectedObject).isFocusAllowed())
{
setInput((IStructure)selectedObject);
}
}
}
}
+ else if (selectedObject instanceof IGraphElement)
+ {
+ if (((IGraphElement)selectedObject).isFocusAllowed())
+ {
+ setInput((IADTObject)selectedObject);
+ }
+ }
else if (selectedObject instanceof IField)
{
IField field = (IField)selectedObject;
if ( (field.isGlobal() && (getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
( (field.isGlobal() && !(getInput() instanceof IModel))))
{
setInput(field);
}
}
else if (selectedObject instanceof IModelProxy)
{
IModelProxy adapter = (IModelProxy)selectedObject;
if (getInput() != adapter.getModel())
setInput(adapter.getModel());
}
else if (selectedObject instanceof IModel)
{
if (getInput() != selectedObject)
setInput((IModel)selectedObject);
}
EditPart editPart = getEditPart(getRootEditPart(), selectedObject);
if (editPart != null)
setSelection(new StructuredSelection(editPart));
}
}
/*
* We need to convert from edit part selections to model object selections
*/
class ADTSelectionChangedListener implements ISelectionProvider, ISelectionChangedListener
{
protected List listenerList = new ArrayList();
protected ISelection selection = new StructuredSelection();
public void addSelectionChangedListener(ISelectionChangedListener listener)
{
listenerList.add(listener);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener)
{
listenerList.remove(listener);
}
public ISelection getSelection()
{
return selection;
}
protected void notifyListeners(SelectionChangedEvent event)
{
for (Iterator i = listenerList.iterator(); i.hasNext();)
{
ISelectionChangedListener listener = (ISelectionChangedListener) i.next();
listener.selectionChanged(event);
}
}
public StructuredSelection convertSelectionFromEditPartToModel(ISelection editPartSelection)
{
List selectedModelObjectList = new ArrayList();
if (editPartSelection instanceof IStructuredSelection)
{
for (Iterator i = ((IStructuredSelection) editPartSelection).iterator(); i.hasNext();)
{
Object obj = i.next();
Object model = null;
if (obj instanceof EditPart)
{
EditPart editPart = (EditPart) obj;
model = editPart.getModel();
}
if (model != null)
{
selectedModelObjectList.add(model);
}
}
}
return new StructuredSelection(selectedModelObjectList);
}
public void setSelection(ISelection selection)
{
this.selection = selection;
}
public void selectionChanged(SelectionChangedEvent event)
{
ISelection newSelection = convertSelectionFromEditPartToModel(event.getSelection());
this.selection = newSelection;
SelectionChangedEvent newEvent = new SelectionChangedEvent(this, newSelection);
notifyListeners(newEvent);
}
}
protected EditPart getEditPart(EditPart parent, Object object)
{
EditPart result = null;
for (Iterator i = parent.getChildren().iterator(); i.hasNext(); )
{
EditPart editPart = (EditPart)i.next();
if (editPart.getModel() == object)
{
result = editPart;
break;
}
}
if (result == null)
{
for (Iterator i = parent.getChildren().iterator(); i.hasNext(); )
{
EditPart editPart = getEditPart((EditPart)i.next(), object);
if (editPart != null)
{
result = editPart;
break;
}
}
}
return result;
}
public void setInput(IADTObject object)
{
RootContentEditPart rootContentEditPart = (RootContentEditPart)getRootEditPart().getContents();
rootContentEditPart.setModel(object);
rootContentEditPart.refresh();
inputChangeManager.setSelection(new StructuredSelection(object));
}
public IADTObject getInput()
{
RootContentEditPart rootContentEditPart = (RootContentEditPart)getRootEditPart().getContents();
return (IADTObject)rootContentEditPart.getModel();
}
public EditPart getInputEditPart()
{
return getRootEditPart().getContents();
}
public void addInputChangdListener(ISelectionChangedListener listener)
{
inputChangeManager.addSelectionChangedListener(listener);
}
public void removeInputChangdListener(ISelectionChangedListener listener)
{
inputChangeManager.removeSelectionChangedListener(listener);
}
private class InputChangeManager implements ISelectionProvider
{
List listeners = new ArrayList();
public void addSelectionChangedListener(ISelectionChangedListener listener)
{
if (!listeners.contains(listener))
{
listeners.add(listener);
}
}
public ISelection getSelection()
{
// no one should be calling this method
return null;
}
public void removeSelectionChangedListener(ISelectionChangedListener listener)
{
listeners.remove(listener);
}
public void setSelection(ISelection selection)
{
notifyListeners(selection);
}
void notifyListeners(ISelection selection)
{
List list = new ArrayList(listeners);
for (Iterator i = list.iterator(); i.hasNext(); )
{
ISelectionChangedListener listener = (ISelectionChangedListener)i.next();
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
}
}
}
| true | true | public void selectionChanged(SelectionChangedEvent event)
{
Object selectedObject = ((StructuredSelection) event.getSelection()).getFirstElement();
// TODO (cs) It seems like there's way more selection going on than there
// should
// be!! There's at least 2 selections getting fired when something is
// selected in the
// outline view. Are we listening to too many things?
//
// if (event.getSource() instanceof ADTContentOutlinePage)
if (event.getSource() != internalSelectionProvider)
{
if (selectedObject instanceof IStructure)
{
if (((getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
(!(getInput() instanceof IModel)))
{
if (selectedObject instanceof IGraphElement)
{
if (((IGraphElement)selectedObject).isFocusAllowed())
{
setInput((IStructure)selectedObject);
}
}
}
}
else if (selectedObject instanceof IField)
{
IField field = (IField)selectedObject;
if ( (field.isGlobal() && (getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
( (field.isGlobal() && !(getInput() instanceof IModel))))
{
setInput(field);
}
}
else if (selectedObject instanceof IModelProxy)
{
IModelProxy adapter = (IModelProxy)selectedObject;
if (getInput() != adapter.getModel())
setInput(adapter.getModel());
}
else if (selectedObject instanceof IModel)
{
if (getInput() != selectedObject)
setInput((IModel)selectedObject);
}
EditPart editPart = getEditPart(getRootEditPart(), selectedObject);
if (editPart != null)
setSelection(new StructuredSelection(editPart));
}
}
| public void selectionChanged(SelectionChangedEvent event)
{
Object selectedObject = ((StructuredSelection) event.getSelection()).getFirstElement();
// TODO (cs) It seems like there's way more selection going on than there
// should
// be!! There's at least 2 selections getting fired when something is
// selected in the
// outline view. Are we listening to too many things?
//
// if (event.getSource() instanceof ADTContentOutlinePage)
if (event.getSource() != internalSelectionProvider)
{
if (selectedObject instanceof IStructure)
{
if (((getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
(!(getInput() instanceof IModel)))
{
if (selectedObject instanceof IGraphElement)
{
if (((IGraphElement)selectedObject).isFocusAllowed())
{
setInput((IStructure)selectedObject);
}
}
}
}
else if (selectedObject instanceof IGraphElement)
{
if (((IGraphElement)selectedObject).isFocusAllowed())
{
setInput((IADTObject)selectedObject);
}
}
else if (selectedObject instanceof IField)
{
IField field = (IField)selectedObject;
if ( (field.isGlobal() && (getInput() instanceof IModel) && (event.getSource() instanceof ADTContentOutlinePage)) ||
( (field.isGlobal() && !(getInput() instanceof IModel))))
{
setInput(field);
}
}
else if (selectedObject instanceof IModelProxy)
{
IModelProxy adapter = (IModelProxy)selectedObject;
if (getInput() != adapter.getModel())
setInput(adapter.getModel());
}
else if (selectedObject instanceof IModel)
{
if (getInput() != selectedObject)
setInput((IModel)selectedObject);
}
EditPart editPart = getEditPart(getRootEditPart(), selectedObject);
if (editPart != null)
setSelection(new StructuredSelection(editPart));
}
}
|
diff --git a/warpdrive-runtime/src/main/java/net/kristianandersen/warpdrive/filter/WarpDriveFilter.java b/warpdrive-runtime/src/main/java/net/kristianandersen/warpdrive/filter/WarpDriveFilter.java
index 569b0dc..e5c9e01 100644
--- a/warpdrive-runtime/src/main/java/net/kristianandersen/warpdrive/filter/WarpDriveFilter.java
+++ b/warpdrive-runtime/src/main/java/net/kristianandersen/warpdrive/filter/WarpDriveFilter.java
@@ -1,68 +1,69 @@
/*
Copyright 2010 Kristian Andersen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.kristianandersen.warpdrive.filter;
import net.kristianandersen.warpdrive.Runtime;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.text.SimpleDateFormat;
/**
* Created by IntelliJ IDEA.
* User: kriand
* Date: Mar 3, 2010
* Time: 9:27:22 PM
* Time: 9:27:22 PM
*/
public class WarpDriveFilter implements Filter {
private final static String EXPIRES_HEADER_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z";
private final static long ONE_YEAR_IN_SECONDS = 31536000L;
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String oneYearFromNow = getOneYearFromNow();
- if(req.getRequestURI().endsWith(Runtime.GZIP_EXTENSION)) {
+ //TODO Improve:
+ if(req.getRequestURI().substring(0, req.getRequestURI().lastIndexOf('.')).endsWith(Runtime.GZIP_EXTENSION)) {
resp.setHeader("Content-Encoding", "gzip");
}
resp.setHeader("Expires", oneYearFromNow);
resp.setHeader("Cache-Control", "max-age=" + ONE_YEAR_IN_SECONDS + ";public;must-revalidate;");
chain.doFilter(req, resp);
}
private String getOneYearFromNow() {
Calendar cal = GregorianCalendar.getInstance();
cal.add(1, Calendar.YEAR);
SimpleDateFormat sdf = new SimpleDateFormat(EXPIRES_HEADER_FORMAT);
return sdf.format(cal.getTime());
}
public void destroy() {
}
}
| true | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String oneYearFromNow = getOneYearFromNow();
if(req.getRequestURI().endsWith(Runtime.GZIP_EXTENSION)) {
resp.setHeader("Content-Encoding", "gzip");
}
resp.setHeader("Expires", oneYearFromNow);
resp.setHeader("Cache-Control", "max-age=" + ONE_YEAR_IN_SECONDS + ";public;must-revalidate;");
chain.doFilter(req, resp);
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String oneYearFromNow = getOneYearFromNow();
//TODO Improve:
if(req.getRequestURI().substring(0, req.getRequestURI().lastIndexOf('.')).endsWith(Runtime.GZIP_EXTENSION)) {
resp.setHeader("Content-Encoding", "gzip");
}
resp.setHeader("Expires", oneYearFromNow);
resp.setHeader("Cache-Control", "max-age=" + ONE_YEAR_IN_SECONDS + ";public;must-revalidate;");
chain.doFilter(req, resp);
}
|
diff --git a/core/src/visad/trunk/ShadowFunctionOrSetType.java b/core/src/visad/trunk/ShadowFunctionOrSetType.java
index 44586ed00..b878c28d7 100644
--- a/core/src/visad/trunk/ShadowFunctionOrSetType.java
+++ b/core/src/visad/trunk/ShadowFunctionOrSetType.java
@@ -1,3261 +1,3265 @@
//
// ShadowFunctionOrSetType.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2000 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
/*
MEM - memory use reduction strategy:
changes marked by MEM_WLH
1. if (isTexture) no assembleSpatial NOT NEEDED
but if (isTexture) then domain_values = null,
so spatial display_values[i] = null so assembleSpatial
does nothing (except construct a SingletonSet spatial_set)
2. byte[][] assembleColor DONE
this has a bad space / time tradeoff in makeIso*,
so create a boolean in GMC to choose between
(Irregular3DSet, Gridded3DSet) and their slower extensions
3. after use, set display_values[i] = null; DONE
done in many ShadowType.assemble* - marked by MEM_WLH
4. don't fill arrays that won't get used
are there any of these ??
5. replace getValues() by getFloats(false)
already done for getSamples
6. assembleColors first DONE
7. boolean[] range_select
8. in-line byteToFloat and floatToByte DONE
VisADCanvasJ2D, Gridded3DSet, Irregular3DSet
N. iso-surface computation uses:
Irregular3DSet.makeIsosurface:
float[len] fieldValues
float[3 or 4][len] auxValues (color_values)
float[3][nvertex] fieldVertices
float[3 or 4][nvertex] auxLevels
int[1][npolygons][3 or 4] polyToVert
int[1][nvertex][nverts[i]] vertToPoly
int[Delan.Tri.length][4] polys
int[Delan.NumEdges] globalToVertex
float[DomainDimension][Delan.NumEdges] edgeInterp
float[3 or 4][Delan.NumEdges] auxInterp
Gridded3DSet.makeIsoSurface:
start with nvertex_estimate = 4 * npolygons + 100
int[num_cubes] ptFLAG
int[xdim_x_ydim_x_zdim] ptAUX
int[num_cubes+1] pcube
float[1][4 * npolygons] VX
float[1][4 * npolygons] VY
float[1][4 * npolygons] VZ
float[3 or 4][nvet] color_temps
float[3 or 4][len] cfloat
int[7 * npolygons] Vert_f_Pol
int[1][36 * npolygons] Pol_f_Vert
number of bytes = 268 (or 284) * npolygons +
24 (or 28) * len
isosurf:
float[3][len] samples
float[3 or 4][nvertex_estimate] tempaux
number of bytes = 48 (or 64) * npolygons +
12 * len
float[npolygons] NxA, NxB, NyA, NyB, NzA, NzB
float[npolygons] Pnx, Pny, Pnz
float[nvertex] NX, NY, NZ
number of bytes = 84 * npolygons
make_normals:
none
total number of bytes = 36 (or 40) * len +
400 (to 432) * npolygons
so if len = 0.5M and npolygons = 0.1M
bytes = 20M + 43.2M = 63.2M
*/
package visad;
import java.util.*;
import java.text.*;
import java.rmi.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBuffer;
import java.awt.image.ComponentColorModel;
import java.awt.color.ColorSpace;
import java.awt.*;
/**
The ShadowFunctionOrSetType class is an abstract parent for
classes that implement ShadowFunctionType or ShadowSetType.<P>
*/
public abstract class ShadowFunctionOrSetType extends ShadowType {
ShadowRealTupleType Domain;
ShadowType Range; // null for ShadowSetType
/** RangeComponents is an array of ShadowRealType-s that are
ShadowRealType components of Range or ShadowRealType
components of ShadowRealTupleType components of Range;
a non-ShadowRealType and non-ShadowTupleType Range is marked
by null;
components of a ShadowTupleType Range that are neither
ShadowRealType nor ShadowRealTupleType are ignored */
ShadowRealType[] RangeComponents; // null for ShadowSetType
ShadowRealType[] DomainComponents;
ShadowRealType[] DomainReferenceComponents;
/** true if range is ShadowRealType or Flat ShadowTupleType
not the same as FunctionType.Flat;
also true for ShadowSetType */
boolean Flat;
/** value_indices from parent */
int[] inherited_values;
/** this constructor is a bit of a kludge to get around
single inheritance problems */
public ShadowFunctionOrSetType(MathType t, DataDisplayLink link, ShadowType parent,
ShadowRealTupleType domain, ShadowType range)
throws VisADException, RemoteException {
super(t, link, parent);
Domain = domain;
Range = range;
if (this instanceof ShadowFunctionType) {
Flat = (Range instanceof ShadowRealType) ||
(Range instanceof ShadowTextType) ||
(Range instanceof ShadowTupleType &&
((ShadowTupleType) Range).isFlat());
MultipleSpatialDisplayScalar = Domain.getMultipleSpatialDisplayScalar() ||
Range.getMultipleSpatialDisplayScalar();
MultipleDisplayScalar = Domain.getMultipleDisplayScalar() ||
Range.getMultipleDisplayScalar();
MappedDisplayScalar = Domain.getMappedDisplayScalar() ||
Range.getMappedDisplayScalar();
RangeComponents = getComponents(Range, true);
}
else if (this instanceof ShadowSetType) {
Flat = true;
MultipleDisplayScalar = Domain.getMultipleDisplayScalar();
MappedDisplayScalar = Domain.getMappedDisplayScalar();
RangeComponents = null;
}
else {
throw new DisplayException("ShadowFunctionOrSetType: must be " +
"ShadowFunctionType or ShadowSetType");
}
DomainComponents = getComponents(Domain, false);
DomainReferenceComponents = getComponents(Domain.getReference(), false);
}
public boolean getFlat() {
return Flat;
}
public ShadowRealType[] getRangeComponents() {
return RangeComponents;
}
public ShadowRealType[] getDomainComponents() {
return DomainComponents;
}
public ShadowRealType[] getDomainReferenceComponents() {
return DomainReferenceComponents;
}
/** used by FlatField.computeRanges */
int[] getRangeDisplayIndices() throws VisADException {
if (!(this instanceof ShadowFunctionType)) {
throw new DisplayException("ShadowFunctionOrSetType.getRangeDisplay" +
"Indices: must be ShadowFunctionType");
}
int n = RangeComponents.length;
int[] indices = new int[n];
for (int i=0; i<n; i++) {
indices[i] = RangeComponents[i].getIndex();
}
return indices;
}
public int[] getInheritedValues() {
return inherited_values;
}
/** checkIndices: check for rendering difficulty, etc */
public int checkIndices(int[] indices, int[] display_indices,
int[] value_indices, boolean[] isTransform, int levelOfDifficulty)
throws VisADException, RemoteException {
// add indices & display_indices from Domain
int[] local_indices = Domain.sumIndices(indices);
int[] local_display_indices = Domain.sumDisplayIndices(display_indices);
int[] local_value_indices = Domain.sumValueIndices(value_indices);
if (Domain.testTransform()) Domain.markTransform(isTransform);
if (this instanceof ShadowFunctionType) {
Range.markTransform(isTransform);
}
// get value_indices arrays used by doTransform
inherited_values = copyIndices(value_indices);
// check for any mapped
if (levelOfDifficulty == NOTHING_MAPPED) {
if (checkAny(local_display_indices)) {
levelOfDifficulty = NESTED;
}
}
// test legality of Animation and SelectValue in Domain
int avCount = checkAnimationOrValue(Domain.getDisplayIndices());
if (Domain.getDimension() != 1) {
if (avCount > 0) {
throw new BadMappingException("Animation and SelectValue may only occur " +
"in 1-D Function domain: " +
"ShadowFunctionOrSetType.checkIndices");
}
else {
// eventually ShadowType.testTransform is used to mark Animation,
// Value or Range as isTransform when multiple occur in Domain;
// however, temporary hack in Renderer.isTransformControl requires
// multiple occurence of Animation and Value to throw an Exception
if (avCount > 1) {
throw new BadMappingException("only one Animation and SelectValue may " +
"occur Set domain: " +
"ShadowFunctionOrSetType.checkIndices");
}
}
}
if (Flat || this instanceof ShadowSetType) {
if (this instanceof ShadowFunctionType) {
if (Range instanceof ShadowTupleType) {
local_indices =
((ShadowTupleType) Range).sumIndices(local_indices);
local_display_indices =
((ShadowTupleType) Range).sumDisplayIndices(local_display_indices);
local_value_indices =
((ShadowTupleType) Range).sumValueIndices(local_value_indices);
}
else if (Range instanceof ShadowScalarType) {
((ShadowScalarType) Range).incrementIndices(local_indices);
local_display_indices = addIndices(local_display_indices,
((ShadowScalarType) Range).getDisplayIndices());
local_value_indices = addIndices(local_value_indices,
((ShadowScalarType) Range).getValueIndices());
}
// test legality of Animation and SelectValue in Range
if (checkAnimationOrValue(Range.getDisplayIndices()) > 0) {
throw new BadMappingException("Animation and SelectValue may not " +
"occur in Function range: " +
"ShadowFunctionOrSetType.checkIndices");
}
} // end if (this instanceof ShadowFunctionType)
anyContour = checkContour(local_display_indices);
anyFlow = checkFlow(local_display_indices);
anyShape = checkShape(local_display_indices);
anyText = checkText(local_display_indices);
LevelOfDifficulty =
testIndices(local_indices, local_display_indices, levelOfDifficulty);
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 1:" +
" LevelOfDifficulty = " + LevelOfDifficulty +
" isTerminal = " + isTerminal +
" Type = " + Type.prettyString());
*/
// compute Domain type
if (!Domain.getMappedDisplayScalar()) {
Dtype = D0;
}
else if (Domain.getAllSpatial() && checkR4(Domain.getDisplayIndices())) {
Dtype = D1;
}
else if (checkR1D3(Domain.getDisplayIndices())) {
Dtype = D3;
}
else if (checkR2D2(Domain.getDisplayIndices())) {
Dtype = D2;
}
else if (checkAnimationOrValue(Domain.getDisplayIndices()) > 0) {
Dtype = D4;
}
else {
Dtype = Dbad;
}
if (this instanceof ShadowFunctionType) {
// compute Range type
if (!Range.getMappedDisplayScalar()) {
Rtype = R0;
}
else if (checkR1D3(Range.getDisplayIndices())) {
Rtype = R1;
}
else if (checkR2D2(Range.getDisplayIndices())) {
Rtype = R2;
}
else if (checkR3(Range.getDisplayIndices())) {
Rtype = R3;
}
else if (checkR4(Range.getDisplayIndices())) {
Rtype = R4;
}
else {
Rtype = Rbad;
}
}
else { // this instanceof ShadowSetType
Rtype = R0; // implicit - Set has no range
}
if (LevelOfDifficulty == NESTED) {
if (Dtype != Dbad && Rtype != Rbad) {
if (Dtype == D4) {
LevelOfDifficulty = SIMPLE_ANIMATE_FIELD;
}
else {
LevelOfDifficulty = SIMPLE_FIELD;
}
}
else {
LevelOfDifficulty = LEGAL;
}
}
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 2:" +
" LevelOfDifficulty = " + LevelOfDifficulty +
" Dtype = " + Dtype + " Rtype = " + Rtype);
*/
if (this instanceof ShadowFunctionType) {
// test for texture mapping
// WLH 30 April 99
isTextureMap = !getMultipleDisplayScalar() &&
getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 2 &&
Domain.getAllSpatial() &&
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
curvedTexture = getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
Domain.getDimension() == 2 &&
Domain.getAllSpatial() &&
checkSpatialOffsetColorAlphaRange(Domain.getDisplayIndices()) &&
checkSpatialOffsetColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
// WLH 15 March 2000
// isTexture3D = !getMultipleDisplayScalar() &&
isTexture3D = getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 3 &&
Domain.getAllSpatial() &&
// WLH 1 April 2000
// !Domain.getMultipleDisplayScalar() && // WLH 15 March 2000
checkSpatialRange(Domain.getDisplayIndices()) && // WLH 1 April 2000
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
// note GgraphicsModeControl.setTextureEnable(false) disables this
isLinearContour3D =
getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 3 &&
Domain.getAllSpatial() &&
!Domain.getMultipleDisplayScalar() &&
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkContourColorAlphaRange(Range.getDisplayIndices()) &&
checkContour(Range.getDisplayIndices());
/*
System.out.println("checkIndices.isTextureMap = " + isTextureMap + " " +
!getMultipleDisplayScalar() + " " +
(getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD) + " " +
((FunctionType) getType()).getReal() + " " +
(Domain.getDimension() == 2) + " " +
Domain.getAllSpatial() + " " +
!Domain.getSpatialReference() + " " +
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) + " " +
checkColorAlphaRange(Range.getDisplayIndices()) + " " +
checkAny(Range.getDisplayIndices()) + " " +
display.getGraphicsModeControl().getTextureEnable() + " " +
!display.getGraphicsModeControl().getPointMode() );
System.out.println("checkIndices.curvedTexture = " + curvedTexture + " " +
(getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD) + " " +
(Domain.getDimension() == 2) + " " +
Domain.getAllSpatial() + " " +
checkSpatialOffsetColorAlphaRange(Domain.getDisplayIndices()) + " " +
checkSpatialOffsetColorAlphaRange(Range.getDisplayIndices()) + " " +
checkAny(Range.getDisplayIndices()) + " " +
display.getGraphicsModeControl().getTextureEnable() + " " +
!display.getGraphicsModeControl().getPointMode() );
*/
}
}
else { // !Flat && this instanceof ShadowFunctionType
if (levelOfDifficulty == NESTED) {
if (!checkNested(Domain.getDisplayIndices())) {
levelOfDifficulty = LEGAL;
}
}
LevelOfDifficulty = Range.checkIndices(local_indices, local_display_indices,
local_value_indices, isTransform,
levelOfDifficulty);
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 3:" +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
}
return LevelOfDifficulty;
}
public ShadowRealTupleType getDomain() {
return Domain;
}
public ShadowType getRange() {
return Range;
}
/** mark Control-s as needing re-Transform */
void markTransform(boolean[] isTransform) {
if (Range != null) Range.markTransform(isTransform);
}
/** transform data into a (Java3D or Java2D) scene graph;
add generated scene graph components as children of group;
group is Group (Java3D) or VisADGroup (Java2D);
value_array are inherited valueArray values;
default_values are defaults for each display.DisplayRealTypeVector;
return true if need post-process */
public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
/* not needed - over-write inherited_values? need to copy?
int[] inherited_values =
((ShadowFunctionOrSetType) adaptedShadowType).getInheritedValues();
*/
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
// System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
float[][] spline_domain = new float[2][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
reference_values = new float[2][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
k++;
}
}
// System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
else {
for (int j=0; j<domain_length; j++) {
text_values[j] = format.format(display_values[i][j]);
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = mode.getMissingTransparent() ? 0 : (byte) -1;
// System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control =
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
} // end if (values != null)
} // end for (int i=0; i<valueArrayLength; i++)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
- for (int i=0; i<valueArrayLength; i++) {
- float[] values = display_values[i];
- if (values != null) {
- int displayScalarIndex = valueToScalar[i];
- DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
- if (real.equals(Display.Animation) ||
- real.equals(Display.SelectValue)) {
- swit = shadow_api.makeSwitch();
- index = i;
- control =
- ((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
- break;
- }
- } // end if (values != null)
- } // end for (int i=0; i<valueArrayLength; i++)
+ if (DomainComponents.length == 1) {
+ RealType real = (RealType) DomainComponents[0].getType();
+ for (int i=0; i<valueArrayLength; i++) {
+ ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
+ float[] values = display_values[i];
+ if (values != null && real.equals(map.getScalar())) {
+ int displayScalarIndex = valueToScalar[i];
+ DisplayRealType dreal =
+ display.getDisplayScalar(displayScalarIndex);
+ if (dreal.equals(Display.Animation) ||
+ dreal.equals(Display.SelectValue)) {
+ swit = shadow_api.makeSwitch();
+ index = i;
+ control = map.getControl();
+ break;
+ }
+ } // end if (values != null && real.equals(map.getScalar()))
+ } // end for (int i=0; i<valueArrayLength; i++)
+ } // end if (DomainComponents.length == 1)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
| true | true | public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
/* not needed - over-write inherited_values? need to copy?
int[] inherited_values =
((ShadowFunctionOrSetType) adaptedShadowType).getInheritedValues();
*/
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
// System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
float[][] spline_domain = new float[2][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
reference_values = new float[2][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
k++;
}
}
// System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
else {
for (int j=0; j<domain_length; j++) {
text_values[j] = format.format(display_values[i][j]);
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = mode.getMissingTransparent() ? 0 : (byte) -1;
// System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control =
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
} // end if (values != null)
} // end for (int i=0; i<valueArrayLength; i++)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control =
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
} // end if (values != null)
} // end for (int i=0; i<valueArrayLength; i++)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
| public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
/* not needed - over-write inherited_values? need to copy?
int[] inherited_values =
((ShadowFunctionOrSetType) adaptedShadowType).getInheritedValues();
*/
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
// System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
float[][] spline_domain = new float[2][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
reference_values = new float[2][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
k++;
}
}
// System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
else {
for (int j=0; j<domain_length; j++) {
text_values[j] = format.format(display_values[i][j]);
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = mode.getMissingTransparent() ? 0 : (byte) -1;
// System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
for (int i=0; i<valueArrayLength; i++) {
float[] values = display_values[i];
if (values != null) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.Animation) ||
real.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control =
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
break;
}
} // end if (values != null)
} // end for (int i=0; i<valueArrayLength; i++)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
|
diff --git a/core/src/visad/trunk/DisplayImpl.java b/core/src/visad/trunk/DisplayImpl.java
index debccd85a..dd7f9747e 100644
--- a/core/src/visad/trunk/DisplayImpl.java
+++ b/core/src/visad/trunk/DisplayImpl.java
@@ -1,3099 +1,3101 @@
//
// DisplayImpl.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2007 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.rmi.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.swing.*;
import visad.browser.Convert;
import visad.browser.Divider;
import visad.util.*;
import visad.collab.ControlMonitorEvent;
import visad.collab.DisplayMonitor;
import visad.collab.DisplayMonitorImpl;
import visad.collab.DisplaySync;
import visad.collab.DisplaySyncImpl;
import visad.collab.MonitorEvent;
/**
DisplayImpl is the abstract VisAD superclass for display
implementations. It is runnable.<P>
DisplayImpl is not Serializable and should not be copied
between JVMs.<P>
*/
public abstract class DisplayImpl extends ActionImpl implements LocalDisplay {
/** instance variables */
/** a Vector of ScalarMap objects;
does not include ConstantMap objects */
private Vector MapVector = new Vector();
/** a Vector of ConstantMap objects */
private Vector ConstantMapVector = new Vector();
/** a Vector of RealType (and TextType) objects occuring
in MapVector */
private Vector RealTypeVector = new Vector();
/** a Vector of DisplayRealType objects occuring in MapVector */
private Vector DisplayRealTypeVector = new Vector();
/** list of Control objects linked to ScalarMap objects in MapVector;
the Control objects may be linked to UI widgets, or just computed */
private Vector ControlVector = new Vector();
/** ordered list of DataRenderer objects that render Data objects */
private Vector RendererVector = new Vector();
/** list of objects interested in learning when DataRenderers
are deleted from this Display */
private Vector RendererSourceListeners = new Vector();
/** list of objects interested in learning when Data objects
are deleted from this Display */
private Vector RmtSrcListeners = new Vector();
/** list of objects interested in receiving messages
from this Display */
private Vector MessageListeners = new Vector();
/** DisplayRenderer object for background and metadata rendering */
private DisplayRenderer displayRenderer;
/** Component where data depictions are rendered;
must be set by concrete subclass constructor;
may be null for off-screen displays */
Component component;
private ComponentChangedListener componentListener = null;
/** set to indicate need to compute ranges of RealType-s
and sampling for Animation */
private boolean initialize = true;
/** set to indicate that ranges should be auto-scaled
every time data are displayed */
private boolean always_initialize = false;
/** set to re-display all linked Data */
private boolean redisplay_all = false;
/** length of ValueArray of distinct DisplayRealType values;
one per Single DisplayRealType that occurs in a ScalarMap,
plus one per ScalarMap per non-Single DisplayRealType;
ScalarMap.valueIndex is an index into ValueArray */
private int valueArrayLength;
/** mapping from ValueArray to DisplayScalar */
private int[] valueToScalar;
/** mapping from ValueArray to MapVector */
private int[] valueToMap;
/** Vector of DisplayListeners */
private final transient Vector ListenerVector = new Vector();
private Object mapslock = new Object();
// WLH 16 March 99
private MouseBehavior mouse = null;
// objects which monitor and synchronize with remote displays
private transient DisplayMonitor displayMonitor = null;
private transient DisplaySync displaySync = null;
// activity monitor
private transient DisplayActivity displayActivity = null;
// Support for printing
private Printable printer;
/**
* construct a DisplayImpl with given name and DisplayRenderer
* @param name String name for DisplayImpl (used for debugging)
* @param renderer DisplayRenderer that controls aspects of the
* display not specific to any particular Data
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public DisplayImpl(String name, DisplayRenderer renderer)
throws VisADException, RemoteException {
super(name);
// put system intrinsic DisplayRealType-s in DisplayRealTypeVector
for (int i=0; i<DisplayRealArray.length; i++) {
DisplayRealTypeVector.addElement(DisplayRealArray[i]);
}
displayMonitor = new DisplayMonitorImpl(this);
displaySync = new DisplaySyncImpl(this);
if (renderer != null) {
displayRenderer = renderer;
} else {
displayRenderer = getDefaultDisplayRenderer();
}
displayRenderer.setDisplay(this);
// initialize ScalarMap's, ShadowDisplayReal's and Control's
clearMaps();
}
/**
* construct a DisplayImpl collaborating with the given RemoteDisplay,
* and with the given DisplayRenderer
* @param rmtDpy RemoteDisplay to collaborate with
* @param renderer DisplayRenderer that controls aspects of the
* display not specific to any particular Data
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public DisplayImpl(RemoteDisplay rmtDpy, DisplayRenderer renderer)
throws VisADException, RemoteException {
// this(rmtDpy, renderer, false);
super(rmtDpy.getName() + ".remote"); // WLH 11 April 2001
// get class used for remote display
String className = rmtDpy.getDisplayClassName();
Class rmtClass;
try {
rmtClass = Class.forName(className);
} catch (ClassNotFoundException cnfe) {
throw new DisplayException("Cannot find remote display class " +
className);
}
// make sure this display class
// is compatible with the remote display class
if (!rmtClass.isInstance(this)) {
throw new DisplayException("Cannot construct " + getClass().getName() +
" from remote " + className);
}
// put system intrinsic DisplayRealType-s in DisplayRealTypeVector
for (int i=0; i<DisplayRealArray.length; i++) {
DisplayRealTypeVector.addElement(DisplayRealArray[i]);
}
displayMonitor = new DisplayMonitorImpl(this);
displaySync = new DisplaySyncImpl(this);
if (renderer != null) {
displayRenderer = renderer;
} else {
try {
String name = rmtDpy.getDisplayRendererClassName();
Object obj = Class.forName(name).newInstance();
displayRenderer = (DisplayRenderer )obj;
} catch (Exception e) {
displayRenderer = getDefaultDisplayRenderer();
}
}
displayRenderer.setDisplay(this);
// initialize ScalarMap's, ShadowDisplayReal's and Control's
clearMaps();
}
// suck in any remote ScalarMaps
void copyScalarMaps(RemoteDisplay rmtDpy)
{
Vector m;
try {
m = rmtDpy.getMapVector();
} catch (Exception e) {
System.err.println("Couldn't copy ScalarMaps");
return;
}
Enumeration me = m.elements();
while (me.hasMoreElements()) {
ScalarMap sm = (ScalarMap )me.nextElement();
try {
addMap((ScalarMap )sm.clone());
} catch (DisplayException de) {
try {
addMap(new ScalarMap(sm.getScalar(), sm.getDisplayScalar()));
} catch (Exception e) {
System.err.println("Couldn't copy remote ScalarMap " + sm);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* copy ConstantMaps from RemoteDisplay to this
* @param rmtDpy RemoteDisplay to get ConstantMaps from
*/
void copyConstantMaps(RemoteDisplay rmtDpy)
{
Vector c;
try {
c = rmtDpy.getConstantMapVector();
} catch (Exception e) {
System.err.println("Couldn't copy ConstantMaps");
return;
}
Enumeration ce = c.elements();
while (ce.hasMoreElements()) {
ConstantMap cm = (ConstantMap )ce.nextElement();
try {
addMap((ConstantMap )cm.clone());
} catch (DisplayException de) {
try {
addMap(new ConstantMap(cm.getConstant(), cm.getDisplayScalar()));
} catch (Exception e) {
System.err.println("Couldn't copy remote ConstantMap " + cm);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* copy GraphicsModeControl settings from RemoteDisplay to this
* @param rmtDpy RemoteDisplay to get GraphicsModeControl settings from
*/
void copyGraphicsModeControl(RemoteDisplay rmtDpy)
{
GraphicsModeControl rc;
try {
getGraphicsModeControl().syncControl(rmtDpy.getGraphicsModeControl());
} catch (UnmarshalException ue) {
System.err.println("Couldn't copy remote GraphicsModeControl");
return;
} catch (java.rmi.ConnectException ce) {
System.err.println("Couldn't copy remote GraphicsModeControl");
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
/**
* copy DataReferences from RemoteDisplay to this
* @param rmtDpy RemoteDisplay to get DataReferences from
* @param localRefs array of DataReferences: don't get any
* DataReference from rmtDpy that has the same
* name as a DataReference in localRefs
*/
private void copyRefLinks(RemoteDisplay rmtDpy, DataReference[] localRefs)
{
Vector ml;
if (rmtDpy == null) return;
try {
ml = rmtDpy.getReferenceLinks();
} catch (UnmarshalException ue) {
System.err.println("Couldn't copy remote DataReferences");
return;
} catch (java.rmi.ConnectException ce) {
System.err.println("Couldn't copy remote DataReferences");
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
String[] refNames;
if (localRefs == null) {
refNames = null;
} else {
refNames = new String[localRefs.length];
for (int i = 0; i < refNames.length; i++) {
try {
refNames[i] = localRefs[i].getName();
} catch (VisADException ve) {
refNames[i] = null;
} catch (RemoteException re) {
refNames[i] = null;
}
}
}
Enumeration mle = ml.elements();
if (mle.hasMoreElements()) {
DataRenderer dr = displayRenderer.makeDefaultRenderer();
String defaultClass = dr.getClass().getName();
while (mle.hasMoreElements()) {
RemoteReferenceLink link = (RemoteReferenceLink )mle.nextElement();
// get reference to Data object
RemoteDataReference ref;
try {
ref = link.getReference();
} catch (Exception e) {
System.err.println("Couldn't copy remote DataReference");
ref = null;
}
if (ref != null && refNames != null) {
String rName;
try {
rName = ref.getName();
} catch (VisADException ve) {
System.err.println("Couldn't get DataReference name");
rName = null;
} catch (RemoteException re) {
System.err.println("Couldn't get remote DataReference name");
rName = null;
}
if (rName != null) {
for (int i = 0; i < refNames.length; i++) {
if (rName.equals(refNames[i])) {
ref = null;
break;
}
}
}
}
if (ref != null) {
// build array of ConstantMap values
ConstantMap[] cm = null;
try {
Vector v = link.getConstantMapVector();
int len = v.size();
if (len > 0) {
cm = new ConstantMap[len];
for (int i = 0; i < len; i++) {
cm[i] = (ConstantMap )v.elementAt(i);
}
}
} catch (Exception e) {
System.err.println("Couldn't copy ConstantMaps" +
" for remote DataReference");
}
// get proper DataRenderer
DataRenderer renderer;
try {
String newClass = link.getRendererClassName();
if (newClass.equals(defaultClass)) {
renderer = null;
} else {
Object obj = Class.forName(newClass).newInstance();
renderer = (DataRenderer )obj;
}
} catch (Exception e) {
System.err.println("Couldn't copy remote DataRenderer name" +
"; using " + defaultClass);
renderer = null;
}
// build RemoteDisplayImpl to which reference is attached
try {
RemoteDisplayImpl rd = new RemoteDisplayImpl(this);
// if this reference uses the default renderer...
if (renderer == null) {
rd.addReference(ref, cm);
} else {
rd.addReferences(renderer, ref, cm);
}
} catch (Exception e) {
System.err.println("Couldn't add remote DataReference " + ref);
}
}
}
}
}
/**
* copy Data from RemoteDisplay to this
* @param rmtDpy RemoteDisplay to get Data from
*/
protected void syncRemoteData(RemoteDisplay rmtDpy)
throws VisADException, RemoteException
{
copyScalarMaps(rmtDpy);
copyConstantMaps(rmtDpy);
copyGraphicsModeControl(rmtDpy);
copyRefLinks(rmtDpy, null);
notifyAction();
waitForTasks();
// only add remote display as listener *after* we've synced
displayMonitor.addRemoteListener(rmtDpy);
initializeControls();
}
// get current state of all controls from remote display(s)
private void initializeControls()
{
ListIterator iter = ControlVector.listIterator();
while (iter.hasNext()) {
try {
Control ctl = (Control )iter.next();
ControlMonitorEvent evt;
evt = new ControlMonitorEvent(MonitorEvent.CONTROL_INIT_REQUESTED,
(Control )ctl.clone());
displayMonitor.notifyListeners(evt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** RemoteDisplayImpl to this for use with remote DisplayListeners */
private RemoteDisplayImpl rd = null;
/**
* Notify this instance's {@link DisplayListener}s.
*
* @param id type of DisplayEvent that is to be sent
* @param x the horizontal x coordinate for the mouse location in
* the display component
* @param y the vertical y coordinate for the mouse location in
* the display component
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
public void notifyListeners(int id, int x, int y)
throws VisADException, RemoteException {
notifyListeners(new DisplayEvent(this, id, x, y));
}
/**
* Notify this instance's {@link DisplayListener}s.
*
* @param evt The {@link DisplayEvent} to be passed to the
* {@link DisplayListener}s.
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
public void notifyListeners(DisplayEvent evt)
throws VisADException, RemoteException {
synchronized (eventStatus) {
if (!eventStatus[evt.getId()]) return; // ignore disabled events
}
for (Enumeration listeners = ((Vector)ListenerVector.clone()).elements();
listeners.hasMoreElements(); ) {
DisplayListener listener = (DisplayListener) listeners.nextElement();
if (listener instanceof Remote) {
if (rd == null) {
rd = new RemoteDisplayImpl(this);
}
listener.displayChanged(evt.cloneButDisplay(rd));
} else {
listener.displayChanged(evt.cloneButDisplay(this));
}
}
}
/**
* add a DisplayListener
* @param listener DisplayListener to add
*/
public void addDisplayListener(DisplayListener listener) {
ListenerVector.addElement(listener);
}
/**
* remove a DisplayListener
* @param listener DisplayListener to remove
*/
public void removeDisplayListener(DisplayListener listener) {
ListenerVector.removeElement(listener);
}
/**
* @return the java.awt.Component (e.g., JPanel or AppletPanel)
* this DisplayImpl uses; returns null for an offscreen
* DisplayImpl
*/
public Component getComponent() {
return component;
}
/**
* set the java.awt.Component this DisplayImpl uses
* @param c Component to set
*/
public void setComponent(Component c) {
if (c != null) {
// lazy initialization
if (componentListener == null) {
componentListener = new ComponentChangedListener(this);
}
c.addComponentListener(componentListener);
}
// in case setComponent is called multiple times
if (component != null) {
if (componentListener != null) {
component.removeComponentListener(componentListener);
}
}
component = c;
}
/**
* request auto-scaling of ScalarMap ranges the next time
* Data are transformed into scene graph elements
*/
public void reAutoScale() {
initialize = true;
// printStack("reAutoScale");
}
/**
* if auto is true, re-apply auto-scaling of ScalarMap ranges
* every time Display is triggered
* @param a flag indicating whether to always re-apply auto-scaling
*/
public void setAlwaysAutoScale(boolean a) {
always_initialize = a;
}
/**
* request all linked Data to be re-transformed into scene graph
* elements
*/
public void reDisplayAll() {
redisplay_all = true;
// printStack("reDisplayAll");
notifyAction();
}
// CTR - begin code for slaved displays
/** Internal list of slaves linked to this display. */
private Vector Slaves = new Vector();
/**
* link a slave display to this
* @param display RemoteSlaveDisplay to link
*/
public void addSlave(RemoteSlaveDisplay display) {
if (!Slaves.contains(display)) Slaves.add(display);
}
/**
* remove a link between a slave display and this
* @param display RemoteSlaveDisplay to remove
*/
public void removeSlave(RemoteSlaveDisplay display) {
if (Slaves.contains(display)) Slaves.remove(display);
}
/**
* remove all links to slave displays
*/
public void removeAllSlaves() {
Slaves.removeAllElements();
}
/**
* @return flag indicating whether there are any slave displays
* linked to this display
*/
public boolean hasSlaves() {
return !Slaves.isEmpty();
}
/**
* update all linked slave displays with the given image
* @param img BufferedImage to send to all linked slave displays
*/
public void updateSlaves(BufferedImage img) {
// extract pixels from image
int width = img.getWidth();
int height = img.getHeight();
int type = img.getType();
int[] pixels = new int[width*height];
img.getRGB(0, 0, width, height, pixels, 0, width);
// encode pixels with RLE
int[] encoded = Convert.encodeRLE(pixels);
synchronized (Slaves) {
// send encoded pixels to each slave
for (int i=0; i<Slaves.size(); i++) {
RemoteSlaveDisplay d = (RemoteSlaveDisplay) Slaves.elementAt(i);
try {
d.sendImage(encoded, width, height, type);
}
catch (java.rmi.ConnectException exc) {
// remote slave client has died; remove it from list
Slaves.remove(i--);
}
catch (RemoteException exc) { }
}
}
}
/**
* update all linked slave display with the given message
* @param message String to send to all linked slave displays
*/
public void updateSlaves(String message) {
synchronized (Slaves) {
// send message to each slave
for (int i=0; i<Slaves.size(); i++) {
RemoteSlaveDisplay d = (RemoteSlaveDisplay) Slaves.elementAt(i);
try {
d.sendMessage(message);
}
catch (java.rmi.ConnectException exc) {
// remote slave client has died; remove it from list
Slaves.remove(i--);
}
catch (RemoteException exc) { }
}
}
}
// CTR - end code for slaved displays
/** Enabled status flag for each DisplayEvent type. */
private final boolean[] eventStatus = {
true, // (not used)
true, // MOUSE_PRESSED
true, // FRAME_DONE
true, // TRANSFORM_DONE
true, // MOUSE_PRESSED_LEFT
true, // MOUSE_PRESSED_CENTER
true, // MOUSE_PRESSED_RIGHT
true, // MOUSE_RELEASED
true, // MOUSE_RELEASED_LEFT
true, // MOUSE_RELEASED_CENTER
true, // MOUSE_RELEASED_RIGHT
true, // MAP_ADDED
true, // MAPS_CLEARED
true, // REFERENCE_ADDED
true, // REFERENCE_REMOVED
true, // DESTROYED
true, // KEY_PRESSED
true, // KEY_RELEASED
false, // MOUSE_DRAGGED
false, // MOUSE_ENTERED
false, // MOUSE_EXITED
false, // MOUSE_MOVED
false, // WAIT_ON
false, // WAIT_OFF
true, // MAP_REMOVED
false, // COMPONENT_RESIZED
};
/**
* Enables reporting of a DisplayEvent of a given type
* when it occurs in this display.
*
* @param id DisplayEvent type to enable. Valid types are:
* <UL>
* <LI>DisplayEvent.FRAME_DONE
* <LI>DisplayEvent.TRANSFORM_DONE
* <LI>DisplayEvent.MOUSE_PRESSED
* <LI>DisplayEvent.MOUSE_PRESSED_LEFT
* <LI>DisplayEvent.MOUSE_PRESSED_CENTER
* <LI>DisplayEvent.MOUSE_PRESSED_RIGHT
* <LI>DisplayEvent.MOUSE_RELEASED_LEFT
* <LI>DisplayEvent.MOUSE_RELEASED_CENTER
* <LI>DisplayEvent.MOUSE_RELEASED_RIGHT
* <LI>DisplayEvent.MAP_ADDED
* <LI>DisplayEvent.MAPS_CLEARED
* <LI>DisplayEvent.REFERENCE_ADDED
* <LI>DisplayEvent.REFERENCE_REMOVED
* <LI>DisplayEvent.DESTROYED
* <LI>DisplayEvent.KEY_PRESSED
* <LI>DisplayEvent.KEY_RELEASED
* <LI>DisplayEvent.MOUSE_DRAGGED
* <LI>DisplayEvent.MOUSE_ENTERED
* <LI>DisplayEvent.MOUSE_EXITED
* <LI>DisplayEvent.MOUSE_MOVED
* <LI>DisplayEvent.WAIT_ON
* <LI>DisplayEvent.WAIT_OFF
* <LI>DisplayEvent.MAP_REMOVED
* <LI>DisplayEvent.COMPONENT_RESIZED
* </UL>
*/
public void enableEvent(int id) {
if (id < 1 || id >= eventStatus.length) return;
synchronized(eventStatus) {
eventStatus[id] = true;
}
}
/**
* Disables reporting of a DisplayEvent of a given type
* when it occurs in this display.
*
* @param id DisplayEvent type to disable. Valid types are:
* <UL>
* <LI>DisplayEvent.FRAME_DONE
* <LI>DisplayEvent.TRANSFORM_DONE
* <LI>DisplayEvent.MOUSE_PRESSED
* <LI>DisplayEvent.MOUSE_PRESSED_LEFT
* <LI>DisplayEvent.MOUSE_PRESSED_CENTER
* <LI>DisplayEvent.MOUSE_PRESSED_RIGHT
* <LI>DisplayEvent.MOUSE_RELEASED_LEFT
* <LI>DisplayEvent.MOUSE_RELEASED_CENTER
* <LI>DisplayEvent.MOUSE_RELEASED_RIGHT
* <LI>DisplayEvent.MAP_ADDED
* <LI>DisplayEvent.MAPS_CLEARED
* <LI>DisplayEvent.REFERENCE_ADDED
* <LI>DisplayEvent.REFERENCE_REMOVED
* <LI>DisplayEvent.DESTROYED
* <LI>DisplayEvent.KEY_PRESSED
* <LI>DisplayEvent.KEY_RELEASED
* <LI>DisplayEvent.MOUSE_DRAGGED
* <LI>DisplayEvent.MOUSE_ENTERED
* <LI>DisplayEvent.MOUSE_EXITED
* <LI>DisplayEvent.MOUSE_MOVED
* <LI>DisplayEvent.WAIT_ON
* <LI>DisplayEvent.WAIT_OFF
* <LI>DisplayEvent.MAP_REMOVED
* <LI>DisplayEvent.COMPONENT_RESIZED
* </UL>
*/
public void disableEvent(int id) {
if (id < 1 || id >= eventStatus.length) return;
synchronized(eventStatus) {
eventStatus[id] = false;
}
}
/**
* @param id DisplayEvent type
* @return flag indicating whether a DisplayEvent of a given
* type is eported when it occurs in this display.
*/
public boolean isEventEnabled(int id) {
if (id < 1 || id >= eventStatus.length) {
return false;
}
else {
synchronized(eventStatus) {
return eventStatus[id];
}
}
}
/**
* Link a reference to this Display.
* This method may only be invoked after all links to
* {@link visad.ScalarMap ScalarMaps}
* have been made.
*
* @param ref data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*/
public void addReference(ThingReference ref)
throws VisADException, RemoteException {
if (!(ref instanceof DataReference)) {
throw new ReferenceException("DisplayImpl.addReference: ref " +
"must be DataReference");
}
if (displayRenderer == null) return;
addReference((DataReference) ref, null);
}
/**
* Replace remote reference with local reference.
*
* @param rDpy Remote display.
* @param ref Local reference which will replace the previous
* reference.
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see visad.DisplayImpl#addReference(visad.ThingReference)
*/
public void replaceReference(RemoteDisplay rDpy, ThingReference ref)
throws VisADException, RemoteException
{
if (!(ref instanceof DataReference)) {
throw new ReferenceException("DisplayImpl.replaceReference: ref " +
"must be DataReference");
}
if (displayRenderer == null) return;
replaceReference(rDpy, (DataReference )ref, null);
}
/**
* Add a link to a DataReference object
*
* @param link The link to the DataReference.
*
* @exception VisADException If referenced data is null
* or if a link already exists.
* @exception RemoteException If a link could not be made
* within the remote display.
*/
void addLink(DataDisplayLink link)
throws VisADException, RemoteException
{
if (displayRenderer == null) return;
addLink(link, true);
}
/**
* Add a link to a DataReference object
*
* @param link The link to the DataReference.
* @param syncRemote <tt>true</tt> if this is not just
* a local link.
*
* @exception VisADException If referenced data is null
* or if a link already exists.
* @exception RemoteException If a link could not be made
* within the remote display.
*/
private void addLink(DataDisplayLink link, boolean syncRemote)
throws VisADException, RemoteException
{
if (displayRenderer == null) return;
// System.out.println("addLink " + getName() + " " +
// link.getData().getType()); // IDV
super.addLink((ReferenceActionLink )link);
if (syncRemote) {
notifyListeners(new DisplayReferenceEvent(this,
DisplayEvent.REFERENCE_ADDED,
link));
}
}
/**
* Link a reference to this Display.
* <tt>ref</tt> must be a local
* {@link visad.DataReferenceImpl DataReferenceImpl}.
* The {@link visad.ConstantMap ConstantMap} array applies only
* to the rendering reference.
*
* @param ref data reference
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with the data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
public void addReference(DataReference ref,
ConstantMap[] constant_maps) throws VisADException, RemoteException {
if (!(ref instanceof DataReferenceImpl)) {
throw new RemoteVisADException("DisplayImpl.addReference: requires " +
"DataReferenceImpl");
}
if (displayRenderer == null) return;
if (findReference(ref) != null) {
throw new TypeException("DisplayImpl.addReference: link already exists");
}
DataRenderer renderer = displayRenderer.makeDefaultRenderer();
DataDisplayLink[] links = {new DataDisplayLink(ref, this, this, constant_maps,
renderer, getLinkId())};
addLink(links[0]);
renderer.setLinks(links, this);
synchronized (mapslock) {
RendererVector.addElement(renderer);
}
initialize |= computeInitialize();
// printStack("addReference");
notifyAction();
}
/**
* Replace remote reference with local reference.
*
* @param rDpy Remote display.
* @param ref Local reference which will replace the previous
* reference.
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with the data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see visad.DisplayImpl#addReference(visad.DataReference, visad.ConstantMap[])
*/
public void replaceReference(RemoteDisplay rDpy, DataReference ref,
ConstantMap[] constant_maps)
throws VisADException, RemoteException
{
if (displayRenderer == null) return;
replaceReferences(rDpy, null, new DataReference[] {ref},
new ConstantMap[][] {constant_maps});
}
/** decide whether an autoscale is needed */
private boolean computeInitialize() {
boolean init = false;
for (Iterator iter = ((java.util.List)MapVector.clone()).iterator();
!init && iter.hasNext();
init |= ((ScalarMap)iter.next()).doInitialize()) {
}
if (!init) {
AnimationControl control =
(AnimationControl) getControl(AnimationControl.class);
if (control != null) {
init |= (control.getSet() == null && control.getComputeSet());
}
}
return init;
}
/**
* Link a RemoteDataReference to this Display.
* The {@link visad.ConstantMap ConstantMap} array applies only
* to the rendering reference.
* For use by addReference() method of RemoteDisplay that adapts this.
*
* @param ref remote data reference
* @param display RemoteDisplay adapting this
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with the data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
void adaptedAddReference(RemoteDataReference ref, RemoteDisplay display,
ConstantMap[] constant_maps) throws VisADException, RemoteException {
if (findReference(ref) != null) {
throw new TypeException("DisplayImpl.adaptedAddReference: " +
"link already exists");
}
if (displayRenderer == null) return;
DataRenderer renderer = displayRenderer.makeDefaultRenderer();
DataDisplayLink[] links = {new DataDisplayLink(ref, this, display, constant_maps,
renderer, getLinkId())};
addLink(links[0]);
renderer.setLinks(links, this);
synchronized (mapslock) {
RendererVector.addElement(renderer);
}
initialize |= computeInitialize();
// printStack("adaptedAddReference");
notifyAction();
}
/**
* Link a reference to this Display using a non-default renderer.
* <tt>ref</tt> must be a local
* {@link visad.DataReferenceImpl DataReferenceImpl}.
* This is a method of {@link visad.DisplayImpl DisplayImpl} and
* {@link visad.RemoteDisplayImpl RemoteDisplayImpl} rather
* than {@link visad.Display Display}
*
* @param renderer logic to render this data
* @param ref data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
public void addReferences(DataRenderer renderer, DataReference ref)
throws VisADException, RemoteException {
addReferences(renderer, new DataReference[] {ref}, null);
}
/**
* Replace remote reference with local reference using
* non-default renderer.
*
* @param rDpy Remote display.
* @param renderer logic to render this data
* @param ref Local reference which will replace the previous
* reference.
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see visad.DisplayImpl#addReferences(visad.DataRenderer, visad.DataReference)
*/
public void replaceReferences(RemoteDisplay rDpy, DataRenderer renderer,
DataReference ref)
throws VisADException, RemoteException
{
replaceReferences(rDpy, renderer, new DataReference[] {ref}, null);
}
/**
* Link a reference to this Display using a non-default renderer.
* <tt>ref</tt> must be a local
* {@link visad.DataReferenceImpl DataReferenceImpl}.
* This is a method of {@link visad.DisplayImpl DisplayImpl} and
* {@link visad.RemoteDisplayImpl RemoteDisplayImpl} rather
* than {@link visad.Display Display}
*
* @param renderer logic to render this data
* @param ref data reference
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with the data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
public void addReferences(DataRenderer renderer, DataReference ref,
ConstantMap[] constant_maps)
throws VisADException, RemoteException {
addReferences(renderer, new DataReference[] {ref},
new ConstantMap[][] {constant_maps});
}
/**
* Replace remote reference with local reference using
* non-default renderer.
*
* @param rDpy Remote display.
* @param renderer logic to render this data
* @param ref Local reference which will replace the previous
* reference.
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with the data reference
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data reference to the remote display.
*
* @see visad.DisplayImpl#addReferences(visad.DataRenderer, visad.DataReference, visad.ConstantMap[])
*/
public void replaceReferences(RemoteDisplay rDpy, DataRenderer renderer,
DataReference ref, ConstantMap[] constant_maps)
throws VisADException, RemoteException
{
replaceReferences(rDpy, renderer, new DataReference[] {ref},
new ConstantMap[][] {constant_maps});
}
/**
* Link references to this display using a non-default renderer.
* <tt>refs</tt> must be local
* {@link visad.DataReferenceImpl DataReferenceImpls}.
* This is a method of {@link visad.DisplayImpl DisplayImpl} and
* {@link visad.RemoteDisplayImpl RemoteDisplayImpl} rather
* than {@link visad.Display Display}
*
* @param renderer logic to render this data
* @param refs array of data references
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
public void addReferences(DataRenderer renderer, DataReference[] refs)
throws VisADException, RemoteException {
addReferences(renderer, refs, null);
}
/**
* Replace remote references with local references.
*
* @param rDpy Remote display.
* @param renderer logic to render this data
* @param refs array of local data references
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see visad.DisplayImpl#addReferences(visad.DataRenderer, visad.DataReference[])
*/
public void replaceReferences(RemoteDisplay rDpy, DataRenderer renderer,
DataReference[] refs)
throws VisADException, RemoteException
{
replaceReferences(rDpy, renderer, refs, null);
}
/**
* Link references to this display using the non-default renderer.
* <tt>refs</tt> must be local
* {@link visad.DataReferenceImpl DataReferenceImpls}.
* The <tt>maps[i]</tt> array applies only to rendering <tt>refs[i]</tt>.
* This is a method of {@link visad.DisplayImpl DisplayImpl} and
* {@link visad.RemoteDisplayImpl RemoteDisplayImpl} rather
* than {@link visad.Display Display}
*
* @param renderer logic to render this data
* @param refs array of data references
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with data references
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
public void addReferences(DataRenderer renderer, DataReference[] refs,
ConstantMap[][] constant_maps)
throws VisADException, RemoteException {
addReferences(renderer, refs, constant_maps, true);
}
/**
* Link references to this display using the non-default renderer.
* <tt>refs</tt> must be local
* {@link visad.DataReferenceImpl DataReferenceImpls}.
* The <tt>maps[i]</tt> array applies only to rendering <tt>refs[i]</tt>.
* This is a method of {@link visad.DisplayImpl DisplayImpl} and
* {@link visad.RemoteDisplayImpl RemoteDisplayImpl} rather
* than {@link visad.Display Display}
*
* @param renderer logic to render this data
* @param refs array of data references
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with data references.
* @param syncRemote <tt>true</tt> if this data should be forwarded
* to the remote display.
*
* @exception VisADException if there was a problem with one or more
* parameters
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
private void addReferences(DataRenderer renderer, DataReference[] refs,
ConstantMap[][] constant_maps,
boolean syncRemote)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
// N.B. This method is called by all replaceReference() methods
if (refs.length < 1) {
throw new DisplayException("DisplayImpl.addReferences: must have at " +
"least one DataReference");
}
if (constant_maps != null && refs.length != constant_maps.length) {
throw new DisplayException("DisplayImpl.addReferences: constant_maps " +
"length must match refs length");
}
if (!displayRenderer.legalDataRenderer(renderer)) {
throw new DisplayException("DisplayImpl.addReferences: illegal " +
"DataRenderer class");
}
DataDisplayLink[] links = new DataDisplayLink[refs.length];
for (int i=0; i< refs.length; i++) {
if (!(refs[i] instanceof DataReferenceImpl)) {
throw new RemoteVisADException("DisplayImpl.addReferences: requires " +
"DataReferenceImpl");
}
if (findReference(refs[i]) != null) {
throw new TypeException("DisplayImpl.addReferences: link already exists");
}
if (constant_maps == null) {
links[i] = new DataDisplayLink(refs[i], this, this, null,
renderer, getLinkId());
}
else {
links[i] = new DataDisplayLink(refs[i], this, this, constant_maps[i],
renderer, getLinkId());
}
addLink(links[i], syncRemote);
}
renderer.setLinks(links, this);
synchronized (mapslock) {
RendererVector.addElement(renderer);
}
initialize |= computeInitialize();
// printStack("addReferences");
notifyAction();
}
/**
* Replace remote references with local references.
*
* @param rDpy Remote display.
* @param renderer logic to render this data
* @param refs array of data references
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with data references.
*
* @exception VisADException if there was a problem with one or more
* parameters.
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see visad.DisplayImpl#addReferences(visad.DataRenderer, visad.DataReference[], visad.ConstantMap[][])
*/
public void replaceReferences(RemoteDisplay rDpy, DataRenderer renderer,
DataReference[] refs,
ConstantMap[][] constant_maps)
throws VisADException, RemoteException
{
if (displayRenderer == null) return;
if (renderer == null) {
renderer = displayRenderer.makeDefaultRenderer();
}
removeAllReferences();
addReferences(renderer, refs, constant_maps, false);
copyRefLinks(rDpy, refs);
}
/**
* Link references to this display using the non-default renderer.
* <tt>refs</tt> may be a mix of local
* {@link visad.DataReferenceImpl DataReferenceImpls} and
* {@link visad.RemoteDataReference RemoteDataReferences}.
* The <tt>maps[i]</tt> array applies only to rendering <tt>refs[i]</tt>.
* For use by addReferences() method of RemoteDisplay that adapts this.
*
* @param renderer logic to render this data
* @param refs array of data references
* @param display RemoteDisplay adapting this
* @param constant_maps array of {@link visad.ConstantMap ConstantMaps}
* associated with data references.
*
* @exception VisADException if there was a problem with one or more
* parameters
* @exception RemoteException if there was a problem adding the
* data references to the remote display.
*
* @see <a href="http://www.ssec.wisc.edu/~billh/guide.html#6.1">Section 6.1 of the Developer's Guide</a>
*/
void adaptedAddReferences(DataRenderer renderer, DataReference[] refs,
RemoteDisplay display, ConstantMap[][] constant_maps)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
if (refs.length < 1) {
throw new DisplayException("DisplayImpl.addReferences: must have at " +
"least one DataReference");
}
if (constant_maps != null && refs.length != constant_maps.length) {
throw new DisplayException("DisplayImpl.addReferences: constant_maps " +
"length must match refs length");
}
if (!displayRenderer.legalDataRenderer(renderer)) {
throw new DisplayException("DisplayImpl.addReferences: illegal " +
"DataRenderer class");
}
DataDisplayLink[] links = new DataDisplayLink[refs.length];
for (int i=0; i< refs.length; i++) {
if (findReference(refs[i]) != null) {
throw new TypeException("DisplayImpl.addReferences: link already exists");
}
if (refs[i] instanceof DataReferenceImpl) {
// refs[i] is local
if (constant_maps == null) {
links[i] = new DataDisplayLink(refs[i], this, this, null,
renderer, getLinkId());
}
else {
links[i] = new DataDisplayLink(refs[i], this, this, constant_maps[i],
renderer, getLinkId());
}
}
else {
// refs[i] is remote
if (constant_maps == null) {
links[i] = new DataDisplayLink(refs[i], this, display, null,
renderer, getLinkId());
}
else {
links[i] = new DataDisplayLink(refs[i], this, display, constant_maps[i],
renderer, getLinkId());
}
}
addLink(links[i]);
}
renderer.setLinks(links, this);
synchronized (mapslock) {
RendererVector.addElement(renderer);
}
initialize |= computeInitialize();
// printStack("adaptedAddReferences");
notifyAction();
}
/**
* remove link to ref, which must be a local DataReferenceImpl;
* if ref was added as part of a DataReference array passed to
* addReferences(), remove links to all of them
* @param ref ThingReference to remove
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void removeReference(ThingReference ref)
throws VisADException, RemoteException {
if (!(ref instanceof DataReferenceImpl)) {
throw new RemoteVisADException("ActionImpl.removeReference: requires " +
"DataReferenceImpl");
}
adaptedDisplayRemoveReference((DataReference) ref);
}
/**
* remove DataDisplayLinks from this DisplayImpl
* @param links array of DataDisplayLinks to remove
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
void removeLinks(DataDisplayLink[] links)
throws RemoteException, VisADException
{
if (displayRenderer == null) return;
for (int i = links.length - 1; i >= 0; i--) {
if (links[i] != null) {
links[i].clearMaps();
}
}
super.removeLinks(links);
}
/**
* remove link to a DataReference;
* uses by removeReference() method of RemoteActionImpl that
* adapts this ActionImpl;
* because DataReference array input to adaptedAddReferences
* may be a mix of local and remote, we tolerate either here
* @param ref DataReference to remove
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
void adaptedDisplayRemoveReference(DataReference ref)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
DataDisplayLink link = (DataDisplayLink) findReference(ref);
// don't throw an Exception if link is null: users may try to
// remove all DataReferences added by a call to addReferences
if (link == null) return;
DataRenderer renderer = link.getRenderer();
DataDisplayLink[] links = renderer.getLinks();
synchronized (mapslock) {
renderer.clearAVControls();
renderer.clearScene();
RendererVector.removeElement(renderer);
}
removeLinks(links);
}
/**
* remove all links to DataReferences
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void removeAllReferences()
throws VisADException, RemoteException {
if (displayRenderer == null) return;
Vector temp = (Vector) RendererVector.clone();
synchronized (mapslock) {
Iterator renderers = temp.iterator();
while (renderers.hasNext()) {
DataRenderer renderer = (DataRenderer) renderers.next();
renderer.clearAVControls();
DataDisplayLink[] links = renderer.getLinks();
renderers.remove();
removeLinks(links);
renderer.clearScene();
}
RendererVector.removeAllElements();
initialize = true;
// printStack("removeAllReferences");
}
}
/**
* trigger possible re-transform of linked Data
* used by Controls to notify this DisplayImpl that they
* have changed
*/
public void controlChanged() {
notifyAction();
}
/**
* over-ride ActionImpl.checkTicks() to always return true,
* since DisplayImpl always runs doAction to find out if any
* linked Data needs to be re-transformed
* @return true
*/
public boolean checkTicks() {
return true;
}
/**
* destroy this display: clear all references to objects
* (so they can be garbage collected), stop all Threads
* and remove all links
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void destroy() throws VisADException, RemoteException {
VisADException thrownVE = null;
RemoteException thrownRE = null;
if (mapslock == null) mapslock = new Object();
synchronized (mapslock) {
stop();
if (displayActivity != null) {
displayActivity.destroy();
}
// tell everybody we're going away
notifyListeners(new DisplayEvent(this, DisplayEvent.DESTROYED));
// remove all listeners
synchronized (ListenerVector) {
ListenerVector.removeAllElements();
}
try {
removeAllReferences();
} catch (RemoteException re) {
thrownRE = re;
} catch (VisADException ve) {
thrownVE = ve;
}
try {
clearMaps();
} catch (RemoteException re) {
thrownRE = re;
} catch (VisADException ve) {
thrownVE = ve;
}
AnimationControl control =
(AnimationControl) getControl(AnimationControl.class);
if (control != null) {
control.stop();
}
if (thrownVE != null) {
throw thrownVE;
}
if (thrownRE != null) {
throw thrownRE;
}
// get rid of dangling references
/* done in clearMaps()
verify (RendererVector == null)
MapVector.removeAllElements();
ConstantMapVector.removeAllElements();
RealTypeVector.removeAllElements();
*/
DisplayRealTypeVector.removeAllElements();
ControlVector.removeAllElements();
RendererSourceListeners.removeAllElements();
RmtSrcListeners.removeAllElements();
MessageListeners.removeAllElements();
ListenerVector.removeAllElements();
Slaves.removeAllElements();
displayRenderer = null; // this disables most DisplayImpl methods
component.removeComponentListener(componentListener);
componentListener = null;
component = null;
mouse = null;
displayMonitor = null;
displaySync = null;
displayActivity = null;
printer = null;
rd = null;
widgetPanel = null;
} // end synchronized (mapslock)
}
/**
* Check if any Data need re-transform, and if so, do it.
* Check if auto-scaling is needed for any ScalarMaps, and
* if so, do it. This method does the real work of DisplayImpl.
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void doAction() throws VisADException, RemoteException {
if (displayRenderer == null) return;
if (mapslock == null) return;
- synchronized (mapslock) {
- if (RendererVector == null || displayRenderer == null) {
- return;
- }
- // put a try/finally block around the setWaitFlag(true), so that we unset
- // the flag before exiting even if an Exception or Error is thrown
- try {
+ // put a try/finally block around the setWaitFlag(true), so that we unset
+ // the flag before exiting even if an Exception or Error is thrown
+ try {
// System.out.println("DisplayImpl call setWaitFlag(true)");
- displayRenderer.setWaitFlag(true);
+ displayRenderer.setWaitFlag(true);
+ synchronized (mapslock) {
+ if (RendererVector == null || displayRenderer == null) {
+// System.out.println("DisplayImpl call setWaitFlag(false)");
+ displayRenderer.setWaitFlag(false);
+ return;
+ }
// set tickFlag-s in changed Control-s
// clone MapVector to avoid need for synchronized access
Vector tmap = (Vector) MapVector.clone();
Enumeration maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.setTicks();
}
// set ScalarMap.valueIndex-s and valueArrayLength
int n = getDisplayScalarCount();
int[] scalarToValue = new int[n];
for (int i=0; i<n; i++) scalarToValue[i] = -1;
valueArrayLength = 0;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
DisplayRealType dreal = map.getDisplayScalar();
map.setValueIndex(valueArrayLength);
valueArrayLength++;
}
// set valueToScalar and valueToMap arrays
valueToScalar = new int[valueArrayLength];
valueToMap = new int[valueArrayLength];
for (int i=0; i<tmap.size(); i++) {
ScalarMap map = (ScalarMap) tmap.elementAt(i);
DisplayRealType dreal = map.getDisplayScalar();
valueToScalar[map.getValueIndex()] = getDisplayScalarIndex(dreal);
valueToMap[map.getValueIndex()] = i;
}
// invoke each DataRenderer (to prepare associated Data objects
// for transformation)
// clone RendererVector to avoid need for synchronized access
Vector temp = ((Vector) RendererVector.clone());
Enumeration renderers = temp.elements();
boolean go = false;
if (initialize) {
renderers = temp.elements();
while (!go && renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
go |= renderer.checkAction();
}
}
/*
System.out.println("initialize = " + initialize + " go = " + go +
" redisplay_all = " + redisplay_all);
*/
if (redisplay_all) {
go = true;
// System.out.println("redisplay_all = " + redisplay_all + " go = " + go);
redisplay_all = false;
}
if (!initialize || go) {
boolean lastinitialize = initialize;
displayRenderer.prepareAction(temp, tmap, go, initialize);
// WLH 10 May 2001
boolean anyBadMap = false;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
if (map.badRange()) {
anyBadMap = true;
// System.out.println("badRange " + map);
}
}
renderers = temp.elements();
boolean badScale = false;
while (renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean badthis = renderer.getBadScale(anyBadMap);
badScale |= badthis;
/*
if (badthis) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("badthis " +
links[0].getThingReference().getName());
}
*/
}
initialize = badScale;
if (always_initialize) initialize = true;
if (initialize && !lastinitialize) {
displayRenderer.prepareAction(temp, tmap, go, initialize);
}
boolean transform_done = false;
// System.out.println("DisplayImpl.doAction transform");
// int i = 0;
boolean any_exceptions = false;
renderers = temp.elements();
while (renderers.hasMoreElements()) {
// System.out.println("DisplayImpl invoke renderer.doAction " + i);
// i++;
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean this_transform = renderer.doAction();
transform_done |= this_transform;
any_exceptions |= !renderer.getExceptionVector().isEmpty();
/*
if (this_transform) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("transform " + getName() + " " +
links[0].getThingReference().getName());
}
*/
}
if (transform_done) {
// System.out.println(getName() + " invoked " + i + " renderers");
AnimationControl control =
(AnimationControl) getControl(AnimationControl.class);
if (control != null) {
control.init();
}
synchronized (ControlVector) {
Enumeration controls = ControlVector.elements();
while(controls.hasMoreElements()) {
Control cont = (Control) controls.nextElement();
if (ValueControl.class.isInstance(cont)) {
((ValueControl) cont).init();
}
}
}
}
if (transform_done || any_exceptions) {
notifyListeners(DisplayEvent.TRANSFORM_DONE, 0, 0);
}
}
// clear tickFlag-s in Control-s
maps = tmap.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.resetTicks();
}
- } finally {
+ } // end synchronized (mapslock)
+ } finally {
// System.out.println("DisplayImpl call setWaitFlag(false)");
- displayRenderer.setWaitFlag(false);
- }
- } // end synchronized (mapslock)
+ displayRenderer.setWaitFlag(false);
+ }
}
/**
* @return the default DisplayRenderer for this DisplayImpl
*/
protected abstract DisplayRenderer getDefaultDisplayRenderer();
/**
* @return the DisplayRenderer associated with this DisplayImpl
*/
public DisplayRenderer getDisplayRenderer() {
return displayRenderer;
}
/**
* Returns a clone of the list of DataRenderer-s. A clone is returned
* to avoid concurrent access problems by the Display thread.
* @return A clone of the list of DataRenderer-s.
* @see #getRenderers()
*/
public Vector getRendererVector() {
return (Vector) RendererVector.clone();
}
/**
* @return the number of DisplayRealTypes in ScalarMaps
* linked to this DisplayImpl
*/
public int getDisplayScalarCount() {
return DisplayRealTypeVector.size();
}
/**
* get the DisplayRealType with the given index
* @param index index into Vector of DisplayRealTypes
* @return the indexed DisplayRealType
*/
public DisplayRealType getDisplayScalar(int index) {
return (DisplayRealType) DisplayRealTypeVector.elementAt(index);
}
/**
* get the index for the given DisplayRealType
* @param dreal DisplayRealType to search for
* @return the index of dreal in Vector of DisplayRealTypes
*/
public int getDisplayScalarIndex(DisplayRealType dreal) {
int dindex;
synchronized (DisplayRealTypeVector) {
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null) {
int n = tuple.getDimension();
for (int i=0; i<n; i++) {
try {
DisplayRealType ereal =
(DisplayRealType) tuple.getComponent(i);
int eindex = DisplayRealTypeVector.indexOf(ereal);
if (eindex < 0) {
DisplayRealTypeVector.addElement(ereal);
}
}
catch (VisADException e) {
}
}
}
dindex = DisplayRealTypeVector.indexOf(dreal);
if (dindex < 0) {
DisplayRealTypeVector.addElement(dreal);
dindex = DisplayRealTypeVector.indexOf(dreal);
}
}
return dindex;
}
/**
* @return the number of ScalarTypes in ScalarMaps
* linked to this DisplayImpl
*/
public int getScalarCount() {
return RealTypeVector.size();
}
/**
* get the ScalarType with the given index
* @param index index into Vector of ScalarTypes
* @return the indexed ScalarType
*/
public ScalarType getScalar(int index) {
return (ScalarType) RealTypeVector.elementAt(index);
}
/**
* get the index for the given ScalarType
* @param real ScalarType to search for
* @return the index of real in Vector of ScalarTypes
* @throws RemoteException an RMI error occurred
*/
public int getScalarIndex(ScalarType real) throws RemoteException {
return RealTypeVector.indexOf(real);
}
/**
* add a ScalarMap to this Display, assuming a local source
* @param map ScalarMap to add
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void addMap(ScalarMap map)
throws VisADException, RemoteException {
addMap(map, VisADEvent.LOCAL_SOURCE);
}
/**
* add a ScalarMap to this Display
* @param map ScalarMap to add
* @param remoteId remote source for collab, or VisADEvent.LOCAL_SOURCE
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void addMap(ScalarMap map, int remoteId)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
synchronized (mapslock) {
int index;
if (!RendererVector.isEmpty()) {
ScalarType st = map.getScalar();
if (st != null) {
Vector temp = (Vector) RendererVector.clone();
Iterator renderers = temp.iterator();
while (renderers.hasNext()) {
DataRenderer renderer = (DataRenderer) renderers.next();
DataDisplayLink[] links = renderer.getLinks();
for (int i=0; i<links.length; i++) {
if (MathType.findScalarType(links[i].getType(), st)) {
/* WLH relax addMap() & clearMap() 17 Dec 2002
throw new DisplayException("DisplayImpl.addMap(): " +
"ScalarType may not occur in any DataReference");
*/
DataReference ref = links[i].getDataReference();
if (ref != null) ref.incTick();
}
}
}
}
}
DisplayRealType type = map.getDisplayScalar();
if (!displayRenderer.legalDisplayScalar(type)) {
throw new BadMappingException("DisplayImpl.addMap: " +
map.getDisplayScalar() + " illegal for this DisplayRenderer");
}
if ((Display.LineWidth.equals(type) ||
Display.PointSize.equals(type) ||
Display.LineStyle.equals(type) ||
Display.TextureEnable.equals(type) ||
Display.MissingTransparent.equals(type) ||
Display.PolygonMode.equals(type) ||
Display.CurvedSize.equals(type) ||
Display.ColorMode.equals(type) ||
Display.PolygonOffset.equals(type) ||
Display.PolygonOffsetFactor.equals(type)) ||
Display.AdjustProjectionSeam.equals(type) ||
Display.Texture3DMode.equals(type) &&
!(map instanceof ConstantMap))
{
throw new BadMappingException("DisplayImpl.addMap: " +
map.getDisplayScalar() + " for ConstantMap only");
}
// System.out.println("addMap " + getName() + " " + map.getScalar() +
// " -> " + map.getDisplayScalar()); // IDV
map.setDisplay(this);
if (map instanceof ConstantMap) {
synchronized (ConstantMapVector) {
Enumeration maps = ConstantMapVector.elements();
while(maps.hasMoreElements()) {
ConstantMap map2 = (ConstantMap) maps.nextElement();
if (map2.getDisplayScalar().equals(map.getDisplayScalar())) {
throw new BadMappingException("Display.addMap: two ConstantMaps " +
"have the same DisplayScalar");
}
}
ConstantMapVector.addElement(map);
}
if (!RendererVector.isEmpty()) {
reDisplayAll(); // WLH 2 April 2002
}
}
else { // !(map instanceof ConstantMap)
// add to RealTypeVector and set ScalarIndex
ScalarType real = map.getScalar();
DisplayRealType dreal = map.getDisplayScalar();
synchronized (MapVector) {
Enumeration maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map2 = (ScalarMap) maps.nextElement();
if (real.equals(map2.getScalar()) &&
dreal.equals(map2.getDisplayScalar()) &&
!dreal.equals(Display.Shape)) {
throw new BadMappingException("Display.addMap: two ScalarMaps " +
"with the same RealType & DisplayRealType");
}
if (dreal.equals(Display.Animation) &&
map2.getDisplayScalar().equals(Display.Animation)) {
throw new BadMappingException("Display.addMap: two RealTypes " +
"are mapped to Animation");
}
}
MapVector.addElement(map);
needWidgetRefresh = true;
}
synchronized (RealTypeVector) {
index = RealTypeVector.indexOf(real);
if (index < 0) {
RealTypeVector.addElement(real);
index = RealTypeVector.indexOf(real);
}
}
map.setScalarIndex(index);
map.setControl();
// WLH 18 June 2002
if (!RendererVector.isEmpty() && map.doInitialize()) {
reAutoScale();
}
} // end !(map instanceof ConstantMap)
addDisplayScalar(map);
notifyListeners(new DisplayMapEvent(this, DisplayEvent.MAP_ADDED, map,
remoteId));
// make sure we monitor all changes to this ScalarMap
map.addScalarMapListener(displayMonitor);
}
}
/**
* remove a ScalarMap from this Display, assuming a local source
* @param map ScalarMap to remove
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void removeMap(ScalarMap map)
throws VisADException, RemoteException {
removeMap(map, VisADEvent.LOCAL_SOURCE);
}
/**
* remove a ScalarMap from this Display
* @param map ScalarMap to add
* @param remoteId remote source for collab, or VisADEvent.LOCAL_SOURCE
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void removeMap(ScalarMap map, int remoteId)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
// System.out.println("removeMap " + getName() + " " + map.getScalar() +
// " -> " + map.getDisplayScalar()); // IDV
synchronized (mapslock) {
// can have multiple equals() maps to Shape, so test for ==
int index = MapVector.indexOf(map);
while (index >=0 && map != MapVector.elementAt(index)) {
index = MapVector.indexOf(map, index+1);
}
if (index < 0) {
throw new BadMappingException("Display.removeMap: " + map + " not " +
"in Display " + getName());
}
MapVector.removeElementAt(index);
ScalarType real = map.getScalar();
if (real != null) {
Enumeration maps = MapVector.elements();
boolean any = false;
while(maps.hasMoreElements()) {
ScalarMap map2 = (ScalarMap) maps.nextElement();
if (real.equals(map2.getScalar())) any = true;
}
if (!any) {
// if real is not used by any other ScalarMap, remove it
// and adjust ScalarIndex of all other ScalarMaps
RealTypeVector.removeElement(real);
maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map2 = (ScalarMap) maps.nextElement();
ScalarType real2 = map2.getScalar();
int index2 = RealTypeVector.indexOf(real2);
if (index2 < 0) {
throw new BadMappingException("Display.removeMap: impossible 1");
}
map2.setScalarIndex(index2);
}
} // end if (!any)
} // end if (real != null)
// trigger events
if (map instanceof ConstantMap) {
if (!RendererVector.isEmpty()) {
reDisplayAll();
}
}
else { // !(map instanceof ConstantMap)
if (!RendererVector.isEmpty()) {
ScalarType st = map.getScalar();
if (st != null) { // not necessary for !(map instanceof ConstantMap)
Vector temp = (Vector) RendererVector.clone();
Iterator renderers = temp.iterator();
while (renderers.hasNext()) {
DataRenderer renderer = (DataRenderer) renderers.next();
DataDisplayLink[] links = renderer.getLinks();
for (int i=0; i<links.length; i++) {
if (MathType.findScalarType(links[i].getType(), st)) {
DataReference ref = links[i].getDataReference();
if (ref != null) ref.incTick();
}
}
}
}
}
// add DRM 2003-02-21
if (map.getAxisScale() != null) {
DisplayRenderer displayRenderer = getDisplayRenderer();
displayRenderer.clearScale(map.getAxisScale());
Enumeration maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map2 = (ScalarMap) maps.nextElement();
AxisScale axisScale = map2.getAxisScale();
if (axisScale != null) {
displayRenderer.clearScale(axisScale);
axisScale.setAxisOrdinal(-1);
}
}
maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map2 = (ScalarMap) maps.nextElement();
AxisScale axisScale = map2.getAxisScale();
if (axisScale != null) {
map2.makeScale();
}
}
}
needWidgetRefresh = true;
} // end !(map instanceof ConstantMap)
notifyListeners(new DisplayMapEvent(this, DisplayEvent.MAP_REMOVED, map,
remoteId));
map.nullDisplay(); // ??
} // end synchronized (mapslock)
}
/**
* add a ScalarType from a ScalarMap from this Display
* @param map ScalarMap whose ScalarType to add
*/
void addDisplayScalar(ScalarMap map) {
int index;
if (displayRenderer == null) return;
DisplayRealType dreal = map.getDisplayScalar();
synchronized (DisplayRealTypeVector) {
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null) {
int n = tuple.getDimension();
for (int i=0; i<n; i++) {
try {
DisplayRealType ereal =
(DisplayRealType) tuple.getComponent(i);
int eindex = DisplayRealTypeVector.indexOf(ereal);
if (eindex < 0) {
DisplayRealTypeVector.addElement(ereal);
}
}
catch (VisADException e) {
}
}
}
index = DisplayRealTypeVector.indexOf(dreal);
if (index < 0) {
DisplayRealTypeVector.addElement(dreal);
index = DisplayRealTypeVector.indexOf(dreal);
}
}
map.setDisplayScalarIndex(index);
}
/**
* remove all ScalarMaps linked this display;
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
public void clearMaps() throws VisADException, RemoteException {
if (displayRenderer == null) return;
// System.out.println("clearMaps " + getName() + "\n"); // IDV
synchronized (mapslock) {
if (!RendererVector.isEmpty()) {
/* WLH relax addMap() & clearMap() 17 Dec 2002
throw new DisplayException("DisplayImpl.clearMaps: RendererVector " +
"must be empty");
*/
reDisplayAll();
}
Enumeration maps;
synchronized (MapVector) {
maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.nullDisplay();
map.removeScalarMapListener(displayMonitor);
}
MapVector.removeAllElements();
needWidgetRefresh = true;
}
synchronized (ConstantMapVector) {
maps = ConstantMapVector.elements();
while(maps.hasMoreElements()) {
ConstantMap map = (ConstantMap) maps.nextElement();
map.nullDisplay();
map.removeScalarMapListener(displayMonitor);
}
ConstantMapVector.removeAllElements();
}
synchronized (ControlVector) {
// clear Control-s associated with this Display
maps = ControlVector.elements();
while(maps.hasMoreElements()) {
Control ctl = (Control )maps.nextElement();
ctl.removeControlListener((ControlListener )displayMonitor);
ctl.setInstanceNumber(-1);
}
ControlVector.removeAllElements();
// one each GraphicsModeControl and ProjectionControl always exists
Control control = (Control) getGraphicsModeControl();
if (control != null) addControl(control);
control = (Control) getProjectionControl();
if (control != null) addControl(control);
// don't forget RendererControl
control = (Control) displayRenderer.getRendererControl();
if (control != null) addControl(control);
}
// clear RealType-s from RealTypeVector
// removeAllElements is synchronized
RealTypeVector.removeAllElements();
synchronized (DisplayRealTypeVector) {
// clear DisplayRealType-s from DisplayRealTypeVector
DisplayRealTypeVector.removeAllElements();
// put system intrinsic DisplayRealType-s in DisplayRealTypeVector
for (int i=0; i<DisplayRealArray.length; i++) {
DisplayRealTypeVector.addElement(DisplayRealArray[i]);
}
}
displayRenderer.clearAxisOrdinals();
displayRenderer.setAnimationString(new String[] {null, null});
}
notifyListeners(new DisplayEvent(this, DisplayEvent.MAPS_CLEARED));
}
/**
* @return clone of Vector of ScalarMaps linked to this DisplayImpl
* (doesn't include ConstantMaps)
*/
public Vector getMapVector() {
return (Vector) MapVector.clone();
}
/**
* @return clone of Vector of ConstantMaps linked to this DisplayImpl
*/
public Vector getConstantMapVector() {
return (Vector) ConstantMapVector.clone();
}
/**
* Get the instance number of this <CODE>Control</CODE>
* in the internal <CODE>ControlVector</CODE>.
*
* @param ctl <CODE>Control</CODE> to look for.
*
* @return Instance number (<CODE>-1</CODE> if not found.)
*/
private int getInstanceNumber(Control ctl)
{
Class ctlClass = ctl.getClass();
int num = 0;
Enumeration en = ControlVector.elements();
while (en.hasMoreElements()) {
Control c = (Control )en.nextElement();
if (ctlClass.isInstance(c)) {
if (ctl == c) {
return num;
}
num++;
}
}
return -1;
}
/**
* Return the ID used to identify the collaborative connection to
* the specified remote display.<br>
* <br>
* <b>WARNING!</b> Due to limitations in the Java RMI implementation,
* this only works with an exact copy of the RemoteDisplay used to
* create the collaboration link.
*
* @param rmtDpy the specified remote display.
* @return <tt>DisplayMonitor.UNKNOWN_LISTENER_ID</tt> if not found;
* otherwise, returns the ID.
* @throws RemoteException an RMI error occurred
*/
public int getConnectionID(RemoteDisplay rmtDpy)
throws RemoteException
{
if (displayMonitor == null) return DisplayMonitor.UNKNOWN_LISTENER_ID;
return displayMonitor.getConnectionID(rmtDpy);
}
/**
* add a Control to this DisplayImpl
* @param control Control to add
*/
public void addControl(Control control) {
if (displayRenderer == null) return;
if (control != null && !ControlVector.contains(control)) {
ControlVector.addElement(control);
control.setIndex(ControlVector.indexOf(control));
control.setInstanceNumber(getInstanceNumber(control));
control.addControlListener((ControlListener )displayMonitor);
}
}
/**
* get a linked Control with the given Class;
* only called for Control objects associated with 'single'
* DisplayRealTypes
* @param c sub-Class of Control to search for
* @return linked Control with Class c, or null
*/
public Control getControl(Class c) { return getControl(c, 0); }
/**
* get ordinal instance of linked Control object of the
* specified class
* @param c sub-Class of Control to search for
* @param inst ordinal instance number
* @return linked Control with Class c, or null
*/
public Control getControl(Class c, int inst) {
return getControls(c, null, inst);
}
/**
* get all linked Control objects of the specified Class
* @param c sub-Class of Control to search for
* @return Vector of linked Controls with Class c
*/
public Vector getControls(Class c) {
Vector v = new Vector();
getControls(c, v, -1);
return v;
}
/**
* Internal method which does the bulk of the work for both
* <CODE>getControl()</CODE> and <CODE>getControls()</CODE>.
* If <CODE>v</CODE> is non-null, adds all <CODE>Control</CODE>s
* of the specified <CODE>Class</CODE> to that <CODE>Vector</CODE>.
* Otherwise, returns <CODE>inst</CODE> instance of the
* <CODE>Control</CODE> matching the specified <CODE>Class</CODE>,
* or <CODE>null</CODE> if no <CODE>Control</CODE> matching the
* criteria is found.
*/
private Control getControls(Class ctlClass, Vector v, int inst)
{
if (displayRenderer == null) return null;
if (ctlClass == null) {
return null;
}
GraphicsModeControl gmc = getGraphicsModeControl();
if (ctlClass.isInstance(gmc)) {
if (v == null) {
return gmc;
}
v.addElement(gmc);
}
else {
synchronized (ControlVector) {
Enumeration en = ControlVector.elements();
while(en.hasMoreElements()) {
Control c = (Control )en.nextElement();
if (ctlClass.isInstance(c)) {
if (v != null) {
v.addElement(c);
} else if (c.getInstanceNumber() == inst) {
return c;
}
}
}
}
}
return null;
}
/**
* @return the total number of controls used by this display
*/
public int getNumberOfControls() { return ControlVector.size(); }
/**
* @return clone of Vector of Controls linked to this DisplayImpl
* @deprecated - DisplayImpl shouldn't expose itself at this level
*/
public Vector getControlVector() {
return (Vector) ControlVector.clone();
}
/** whether the Control widget panel needs to be reconstructed */
private boolean needWidgetRefresh = true;
/** this Display's associated panel of Control widgets */
private JPanel widgetPanel = null;
/**
* get a GUI component containing this Display's Control widgets;
* create the widgets as necessary
* @return Container of widget panel
*/
public Container getWidgetPanel() {
if (displayRenderer == null) return null;
if (needWidgetRefresh) {
synchronized (MapVector) {
// construct widget panel if needed
if (widgetPanel == null) {
widgetPanel = new JPanel();
widgetPanel.setLayout(new BoxLayout(widgetPanel, BoxLayout.Y_AXIS));
}
else widgetPanel.removeAll();
if (getLinks().size() > 0) {
// GraphicsModeControl widget
GMCWidget gmcw = new GMCWidget(getGraphicsModeControl());
addToWidgetPanel(gmcw, false);
}
for (int i=0; i<MapVector.size(); i++) {
ScalarMap sm = (ScalarMap) MapVector.elementAt(i);
DisplayRealType drt = sm.getDisplayScalar();
try {
double[] a = new double[2];
double[] b = new double[2];
double[] c = new double[2];
boolean scale = sm.getScale(a, b, c);
if (scale) {
// ScalarMap range widget
RangeWidget rw = new RangeWidget(sm);
addToWidgetPanel(rw, true);
}
}
catch (VisADException exc) { }
try {
if (drt.equals(Display.RGB) || drt.equals(Display.RGBA)) {
// ColorControl widget
try {
LabeledColorWidget lw = new LabeledColorWidget(sm);
addToWidgetPanel(lw, true);
}
catch (VisADException exc) { }
catch (RemoteException exc) { }
}
else if (drt.equals(Display.SelectValue)) {
// ValueControl widget
VisADSlider vs = new VisADSlider(sm);
vs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
addToWidgetPanel(vs, true);
}
else if (drt.equals(Display.SelectRange)) {
// RangeControl widget
SelectRangeWidget srw = new SelectRangeWidget(sm);
addToWidgetPanel(srw, true);
}
else if (drt.equals(Display.IsoContour)) {
// ContourControl widget
ContourWidget cw = new ContourWidget(sm);
addToWidgetPanel(cw, true);
}
else if (drt.equals(Display.Animation)) {
// AnimationControl widget
AnimationWidget aw = new AnimationWidget(sm);
addToWidgetPanel(aw, true);
}
}
catch (VisADException exc) { }
catch (RemoteException exc) { }
}
}
needWidgetRefresh = false;
}
return widgetPanel;
}
/** add a component to the widget panel */
private void addToWidgetPanel(Component c, boolean divide) {
if (displayRenderer == null) return;
if (divide) widgetPanel.add(new Divider());
widgetPanel.add(c);
}
/**
* @return length of valueArray passed to ShadowType.doTransform()
*/
public int getValueArrayLength() {
return valueArrayLength;
}
/**
* @return int[] array mapping from valueArray indices to
* ScalarType Vector indices
*/
public int[] getValueToScalar() {
return valueToScalar;
}
/**
* @return int[] array mapping from valueArray indices to
* ScalarMap Vector indices
*/
public int[] getValueToMap() {
return valueToMap;
}
/**
* @return the ProjectionControl associated with this DisplayImpl
*/
public abstract ProjectionControl getProjectionControl();
/**
* @return the GraphicsModeControl associated with this DisplayImpl
*/
public abstract GraphicsModeControl getGraphicsModeControl();
/**
* wait for millis milliseconds
* @param millis number of milliseconds to wait
* @deprecated Use <CODE>new visad.util.Delay(millis)</CODE> instead.
*/
public static void delay(int millis) {
new visad.util.Delay(millis);
}
/**
* print a stack dump with the given message
* @param message String to print with stack dump
*/
public static void printStack(String message) {
try {
throw new DisplayException("printStack: " + message);
}
catch (DisplayException e) {
e.printStackTrace();
}
}
/**
* test for equality between this and the given Object
* given their complexity, its reasonable that DisplayImpl
* objects are only equal to themselves
* @param obj Object to test for equality with this
* @return flag indicating whether this is equal to obj
*/
public boolean equals(Object obj) {
return (obj == this);
}
/**
* Returns the list of DataRenderer-s. NOTE: The actual list is returned
* rather than a copy. If a copy is desired, then use
* <code>getRendererVector()</code>.
* @return The list of DataRenderer-s.
* @see #getRendererVector()
*/
public Vector getRenderers()
{
return (Vector )RendererVector.clone();
}
/**
* Return the API used for this display
*
* @return the mode being used (UNKNOWN, JPANEL, APPLETFRAME,
* OFFSCREEN, TRANSFORM_ONLY)
* @throws VisADException
*/
public int getAPI()
throws VisADException
{
throw new VisADException("No API specified");
}
/**
* @return the <CODE>DisplayMonitor</CODE> associated with this
* <CODE>Display</CODE>.
*/
public DisplayMonitor getDisplayMonitor()
{
return displayMonitor;
}
/**
* @return the <CODE>DisplaySync</CODE> associated with this
* <CODE>Display</CODE>.
*/
public DisplaySync getDisplaySync()
{
return displaySync;
}
/**
* set given MouseBehavior
* @param m MouseBehavior to set
*/
public void setMouseBehavior(MouseBehavior m) {
mouse = m;
}
/**
* @return the MouseBehavior used for this Display
*/
public MouseBehavior getMouseBehavior() {
return mouse;
}
/**
* make projection matrix from given arguments
* @param rotx rotation about x axis
* @param roty rotation about y axis
* @param rotz rotation about z axis
* @param scale linear scale factor
* @param transx translation along x axis
* @param transy translation along y axis
* @param transz translation along z axis
*/
public double[] make_matrix(double rotx, double roty, double rotz,
double scale, double transx, double transy, double transz) {
if (mouse != null) {
return mouse.make_matrix(rotx, roty, rotz, scale, transx, transy, transz);
}
else {
return null;
}
}
/**
* multiply matrices
* @param a first operand matrix
* @param b second operand matrix
* @return product matrix
*/
public double[] multiply_matrix(double[] a, double[] b) {
if (mouse != null && a != null && b != null) {
return mouse.multiply_matrix(a, b);
}
else {
return null;
}
}
/**
* get a BufferedImage of this Display, without synchronizing
* (assume the application has made sure Data have been
* transformed and rendered)
* @return a captured image of this Display
*/
public BufferedImage getImage() {
return getImage(false);
}
/**
* get a BufferedImage of this Display
* @param sync if true, ensure that all linked Data have been
* transformed and rendered
* @return a captured image of this Display
*/
public BufferedImage getImage(boolean sync) {
if (displayRenderer == null) return null;
Thread thread = Thread.currentThread();
String name = thread.getName();
if (thread.equals(getCurrentActionThread()) ||
name.startsWith("J3D-Renderer") ||
name.startsWith("AWT-EventQueue")) {
throw new VisADError("cannot call getImage() from Thread: " + name);
}
if (sync) new Syncher(this);
return displayRenderer.getImage();
}
/**
* @return a String representation of this Display
*/
public String toString() {
return toString("");
}
/**
* @param pre String added to start of each line
* @return a String representation of this Display
* indented by pre (a string of blanks)
*/
public String toString(String pre) {
String s = pre + "Display\n";
Enumeration maps = MapVector.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
s = s + map.toString(pre + " ");
}
maps = ConstantMapVector.elements();
while(maps.hasMoreElements()) {
ConstantMap map = (ConstantMap) maps.nextElement();
s = s + map.toString(pre + " ");
}
return s;
}
protected void finalize() throws Throwable {
destroy();
}
/** Class used to ensure that all linked Data have been
transformed and rendered, used by getImage() */
public class Syncher extends Object implements DisplayListener {
private ProjectionControl control;
int count;
/**
* construct a Syncher for the given DisplayImpl
* @param display DisplayImpl for this Syncher
*/
Syncher(DisplayImpl display) {
try {
synchronized (this) {
control = display.getProjectionControl();
count = -1;
display.disableAction();
display.addDisplayListener(this);
display.reDisplayAll();
display.enableAction();
this.wait();
}
}
catch(InterruptedException e) {
}
display.removeDisplayListener(this);
}
/**
* process DisplayEvent
* @param e DisplayEvent to process
*/
public void displayChanged(DisplayEvent e)
throws VisADException, RemoteException {
if (e.getId() == DisplayEvent.TRANSFORM_DONE) {
count = 2;
control.setMatrix(control.getMatrix());
}
else if (e.getId() == DisplayEvent.FRAME_DONE) {
if (count > 0) {
control.setMatrix(control.getMatrix());
count--;
}
else if (count == 0) {
synchronized (this) {
this.notify();
}
count--;
}
}
}
}
/**
* Return the Printable object to be used by a PrinterJob. This can
* be used as follows:
* <pre>
* PrinterJob printJob = PrinterJob.getPrinterJob();
* PageFormat pf = printJob.defaultPage();
* printJob.setPrintable(display.getPrintable(), pf);
* if (printJob.printDialog()) {
* try {
* printJob.print();
* }
* catch (Exception pe) {
* pe.printStackTrace();
* }
* }
* </pre>
*
* @return printable object
*/
public Printable getPrintable()
{
if (printer == null)
printer =
new Printable() {
public int print(Graphics g, PageFormat pf, int pi)
throws PrinterException
{
if (pi >= 1)
{
return Printable.NO_SUCH_PAGE;
}
BufferedImage image = DisplayImpl.this.getImage();
g.drawImage(
image,
(int) pf.getImageableX(),
(int) pf.getImageableY(),
DisplayImpl.this.component);
return Printable.PAGE_EXISTS;
}
};
return printer;
}
/**
* handle DisconnectException for the given ReferenceActionLink
* @param raLink ReferenceActionLink with DisconnectException
*/
void handleRunDisconnectException(ReferenceActionLink raLink)
{
if (!(raLink instanceof DataDisplayLink)) {
return;
}
DataDisplayLink link = (DataDisplayLink )raLink;
}
/**
* Notify this Display that a connection to a remote server has failed
* @param renderer DataRenderer with failure
* @param link DataDisplayLink with failure
*/
public void connectionFailed(DataRenderer renderer, DataDisplayLink link)
{
try {
removeLinks(new DataDisplayLink[] { link });
} catch (VisADException ve) {
ve.printStackTrace();
} catch (RemoteException re) {
re.printStackTrace();
}
if (renderer != null) {
DataDisplayLink[] links = renderer.getLinks();
if (links.length <= 1) {
deleteRenderer(renderer);
}
}
Enumeration en = RmtSrcListeners.elements();
while (en.hasMoreElements()) {
RemoteSourceListener l = (RemoteSourceListener )en.nextElement();
l.dataSourceLost(link.getName());
}
}
/**
* Inform <tt>listener</tt> of deleted {@link DataRenderer}s.
*
* @param listener Object to add.
*/
public void addRendererSourceListener(RendererSourceListener listener)
{
RendererSourceListeners.addElement(listener);
}
/**
* Remove <tt>listener</tt> from the {@link DataRenderer} deletion list.
*
* @param listener Object to remove.
*/
public void removeRendererSourceListener(RendererSourceListener listener)
{
RendererSourceListeners.removeElement(listener);
}
/**
* Stop using a {@link DataRenderer}.
*
* @param renderer Renderer to delete
*/
private void deleteRenderer(DataRenderer renderer)
{
RendererVector.removeElement(renderer);
Enumeration en = RendererSourceListeners.elements();
while (en.hasMoreElements()) {
((RendererSourceListener )en.nextElement()).rendererDeleted(renderer);
}
}
/**
* @deprecated
*/
public void addDataSourceListener(RemoteSourceListener listener)
{
addRemoteSourceListener(listener);
}
/**
* @deprecated
*/
public void removeDataSourceListener(RemoteSourceListener listener)
{
removeRemoteSourceListener(listener);
}
/**
* Inform <tt>listener</tt> of changes in the availability
* of remote data/collaboration sources.
*
* @param listener Object to send change notifications.
*/
public void addRemoteSourceListener(RemoteSourceListener listener)
{
RmtSrcListeners.addElement(listener);
}
/**
* Remove <tt>listener</tt> from the remote source notification list.
*
* @param listener Object to be removed.
*/
public void removeRemoteSourceListener(RemoteSourceListener listener)
{
RmtSrcListeners.removeElement(listener);
}
/**
* Inform {@link RemoteSourceListener}s that the specified collaborative
* connection has been lost.<br>
* <br>
* <b>WARNING!</b> This should only be called from within the
* visad.collab package!
*
* @param id ID of lost connection.
*/
public void lostCollabConnection(int id)
{
Enumeration en = RmtSrcListeners.elements();
while (en.hasMoreElements()) {
((RemoteSourceListener )en.nextElement()).collabSourceLost(id);
}
}
/**
* Forward messages to the specified <tt>listener</tt>
*
* @param listener New message receiver.
*/
public void addMessageListener(MessageListener listener)
{
MessageListeners.addElement(listener);
}
/**
* Remove <tt>listener</tt> from the message list.
*
* @param listener Object to remove.
*/
public void removeMessageListener(MessageListener listener)
{
MessageListeners.removeElement(listener);
}
/**
* Send a message to all </tt>MessageListener</tt>s.
*
* @param msg Message being sent.
*/
public void sendMessage(MessageEvent msg)
throws RemoteException
{
RemoteException exception = null;
Enumeration en = MessageListeners.elements();
while (en.hasMoreElements()) {
MessageListener l = (MessageListener )en.nextElement();
try {
l.receiveMessage(msg);
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
// remote side disconnected; forget about it
MessageListeners.removeElement(l);
} else {
// save this exception for later
exception = re;
}
}
}
if (exception != null) {
throw exception;
}
}
/**
* set aspect ratio of XAxis, YAxis & ZAxis in ScalarMaps rather
* than matrix (i.e., don't distort text fonts); called by
* ProjectionControl.setAspectCartesian()
* @param aspect ratios; 3 elements for Java3D, 2 for Java2D
* @throws VisADException a VisAD error occurred
* @throws RemoteException an RMI error occurred
*/
void setAspectCartesian(double[] aspect)
throws VisADException, RemoteException {
if (displayRenderer == null) return;
if (mapslock == null) return;
synchronized (mapslock) {
// clone MapVector to avoid need for synchronized access
Vector tmap = (Vector) MapVector.clone();
Enumeration maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.setAspectCartesian(aspect);
}
tmap = (Vector) ConstantMapVector.clone();
maps = tmap.elements();
while (maps.hasMoreElements()) {
ConstantMap map = (ConstantMap) maps.nextElement();
map.setAspectCartesian(aspect);
}
// resize box
getDisplayRenderer().setBoxAspect(aspect);
// reAutoScale(); ??
reDisplayAll();
} // end synchronized (mapslock)
}
/**
* Add a busy/idle activity handler.
*
* @param ah Activity handler.
*
* @throws VisADException If the handler couldn't be added.
*/
public void addActivityHandler(ActivityHandler ah)
throws VisADException
{
if (displayRenderer == null) return;
if (displayActivity == null) {
displayActivity = new DisplayActivity(this);
}
displayActivity.addHandler(ah);
}
/**
* Remove a busy/idle activity handler.
*
* @param ah Activity handler.
*
* @throws VisADException If the handler couldn't be removed.
*/
public void removeActivityHandler(ActivityHandler ah)
throws VisADException
{
if (displayRenderer == null) return;
if (displayActivity == null) {
displayActivity = new DisplayActivity(this);
}
displayActivity.removeHandler(ah);
}
/**
* Indicate to activity monitor that the Display is busy.
*/
public void updateBusyStatus()
{
if (displayActivity != null) {
displayActivity.updateBusyStatus();
}
}
/** Class for listening to component events */
private class ComponentChangedListener extends ComponentAdapter {
/** the listener's display*/
DisplayImpl display;
/**
* Create a listener for the display
*/
public ComponentChangedListener(DisplayImpl d) {
display = d;
}
/**
* Invoked when the component has been resized.
* @param ce ComponentEvent fired.
*/
public void componentShown(ComponentEvent ce) {}
/**
* Invoked when the component has been made invisible.
* @param ce ComponentEvent fired.
*/
public void componentHidden(ComponentEvent ce) {}
/**
* Invoked when the component has been moved.
* @param ce ComponentEvent fired.
*/
public void componentMoved(ComponentEvent ce) {}
/**
* Invoked when the component has been resized.
* @param ce ComponentEvent fired.
*/
public void componentResized(ComponentEvent ce) {
Component component = ce.getComponent();
Dimension d = component.getSize();
try {
notifyListeners(
new DisplayEvent(
display, DisplayEvent.COMPONENT_RESIZED, d.width, d.height));
}
catch (VisADException ve) {
System.err.println("Couldn't notify listeners of resize event");
}
catch (RemoteException re) {
System.err.println("Couldn't notify listeners of remote resize event");
}
}
}
}
| false | true | public void doAction() throws VisADException, RemoteException {
if (displayRenderer == null) return;
if (mapslock == null) return;
synchronized (mapslock) {
if (RendererVector == null || displayRenderer == null) {
return;
}
// put a try/finally block around the setWaitFlag(true), so that we unset
// the flag before exiting even if an Exception or Error is thrown
try {
// System.out.println("DisplayImpl call setWaitFlag(true)");
displayRenderer.setWaitFlag(true);
// set tickFlag-s in changed Control-s
// clone MapVector to avoid need for synchronized access
Vector tmap = (Vector) MapVector.clone();
Enumeration maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.setTicks();
}
// set ScalarMap.valueIndex-s and valueArrayLength
int n = getDisplayScalarCount();
int[] scalarToValue = new int[n];
for (int i=0; i<n; i++) scalarToValue[i] = -1;
valueArrayLength = 0;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
DisplayRealType dreal = map.getDisplayScalar();
map.setValueIndex(valueArrayLength);
valueArrayLength++;
}
// set valueToScalar and valueToMap arrays
valueToScalar = new int[valueArrayLength];
valueToMap = new int[valueArrayLength];
for (int i=0; i<tmap.size(); i++) {
ScalarMap map = (ScalarMap) tmap.elementAt(i);
DisplayRealType dreal = map.getDisplayScalar();
valueToScalar[map.getValueIndex()] = getDisplayScalarIndex(dreal);
valueToMap[map.getValueIndex()] = i;
}
// invoke each DataRenderer (to prepare associated Data objects
// for transformation)
// clone RendererVector to avoid need for synchronized access
Vector temp = ((Vector) RendererVector.clone());
Enumeration renderers = temp.elements();
boolean go = false;
if (initialize) {
renderers = temp.elements();
while (!go && renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
go |= renderer.checkAction();
}
}
/*
System.out.println("initialize = " + initialize + " go = " + go +
" redisplay_all = " + redisplay_all);
*/
if (redisplay_all) {
go = true;
// System.out.println("redisplay_all = " + redisplay_all + " go = " + go);
redisplay_all = false;
}
if (!initialize || go) {
boolean lastinitialize = initialize;
displayRenderer.prepareAction(temp, tmap, go, initialize);
// WLH 10 May 2001
boolean anyBadMap = false;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
if (map.badRange()) {
anyBadMap = true;
// System.out.println("badRange " + map);
}
}
renderers = temp.elements();
boolean badScale = false;
while (renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean badthis = renderer.getBadScale(anyBadMap);
badScale |= badthis;
/*
if (badthis) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("badthis " +
links[0].getThingReference().getName());
}
*/
}
initialize = badScale;
if (always_initialize) initialize = true;
if (initialize && !lastinitialize) {
displayRenderer.prepareAction(temp, tmap, go, initialize);
}
boolean transform_done = false;
// System.out.println("DisplayImpl.doAction transform");
// int i = 0;
boolean any_exceptions = false;
renderers = temp.elements();
while (renderers.hasMoreElements()) {
// System.out.println("DisplayImpl invoke renderer.doAction " + i);
// i++;
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean this_transform = renderer.doAction();
transform_done |= this_transform;
any_exceptions |= !renderer.getExceptionVector().isEmpty();
/*
if (this_transform) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("transform " + getName() + " " +
links[0].getThingReference().getName());
}
*/
}
if (transform_done) {
// System.out.println(getName() + " invoked " + i + " renderers");
AnimationControl control =
(AnimationControl) getControl(AnimationControl.class);
if (control != null) {
control.init();
}
synchronized (ControlVector) {
Enumeration controls = ControlVector.elements();
while(controls.hasMoreElements()) {
Control cont = (Control) controls.nextElement();
if (ValueControl.class.isInstance(cont)) {
((ValueControl) cont).init();
}
}
}
}
if (transform_done || any_exceptions) {
notifyListeners(DisplayEvent.TRANSFORM_DONE, 0, 0);
}
}
// clear tickFlag-s in Control-s
maps = tmap.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.resetTicks();
}
} finally {
// System.out.println("DisplayImpl call setWaitFlag(false)");
displayRenderer.setWaitFlag(false);
}
} // end synchronized (mapslock)
}
| public void doAction() throws VisADException, RemoteException {
if (displayRenderer == null) return;
if (mapslock == null) return;
// put a try/finally block around the setWaitFlag(true), so that we unset
// the flag before exiting even if an Exception or Error is thrown
try {
// System.out.println("DisplayImpl call setWaitFlag(true)");
displayRenderer.setWaitFlag(true);
synchronized (mapslock) {
if (RendererVector == null || displayRenderer == null) {
// System.out.println("DisplayImpl call setWaitFlag(false)");
displayRenderer.setWaitFlag(false);
return;
}
// set tickFlag-s in changed Control-s
// clone MapVector to avoid need for synchronized access
Vector tmap = (Vector) MapVector.clone();
Enumeration maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.setTicks();
}
// set ScalarMap.valueIndex-s and valueArrayLength
int n = getDisplayScalarCount();
int[] scalarToValue = new int[n];
for (int i=0; i<n; i++) scalarToValue[i] = -1;
valueArrayLength = 0;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
DisplayRealType dreal = map.getDisplayScalar();
map.setValueIndex(valueArrayLength);
valueArrayLength++;
}
// set valueToScalar and valueToMap arrays
valueToScalar = new int[valueArrayLength];
valueToMap = new int[valueArrayLength];
for (int i=0; i<tmap.size(); i++) {
ScalarMap map = (ScalarMap) tmap.elementAt(i);
DisplayRealType dreal = map.getDisplayScalar();
valueToScalar[map.getValueIndex()] = getDisplayScalarIndex(dreal);
valueToMap[map.getValueIndex()] = i;
}
// invoke each DataRenderer (to prepare associated Data objects
// for transformation)
// clone RendererVector to avoid need for synchronized access
Vector temp = ((Vector) RendererVector.clone());
Enumeration renderers = temp.elements();
boolean go = false;
if (initialize) {
renderers = temp.elements();
while (!go && renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
go |= renderer.checkAction();
}
}
/*
System.out.println("initialize = " + initialize + " go = " + go +
" redisplay_all = " + redisplay_all);
*/
if (redisplay_all) {
go = true;
// System.out.println("redisplay_all = " + redisplay_all + " go = " + go);
redisplay_all = false;
}
if (!initialize || go) {
boolean lastinitialize = initialize;
displayRenderer.prepareAction(temp, tmap, go, initialize);
// WLH 10 May 2001
boolean anyBadMap = false;
maps = tmap.elements();
while (maps.hasMoreElements()) {
ScalarMap map = ((ScalarMap) maps.nextElement());
if (map.badRange()) {
anyBadMap = true;
// System.out.println("badRange " + map);
}
}
renderers = temp.elements();
boolean badScale = false;
while (renderers.hasMoreElements()) {
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean badthis = renderer.getBadScale(anyBadMap);
badScale |= badthis;
/*
if (badthis) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("badthis " +
links[0].getThingReference().getName());
}
*/
}
initialize = badScale;
if (always_initialize) initialize = true;
if (initialize && !lastinitialize) {
displayRenderer.prepareAction(temp, tmap, go, initialize);
}
boolean transform_done = false;
// System.out.println("DisplayImpl.doAction transform");
// int i = 0;
boolean any_exceptions = false;
renderers = temp.elements();
while (renderers.hasMoreElements()) {
// System.out.println("DisplayImpl invoke renderer.doAction " + i);
// i++;
DataRenderer renderer = (DataRenderer) renderers.nextElement();
boolean this_transform = renderer.doAction();
transform_done |= this_transform;
any_exceptions |= !renderer.getExceptionVector().isEmpty();
/*
if (this_transform) {
DataDisplayLink[] links = renderer.getLinks();
System.out.println("transform " + getName() + " " +
links[0].getThingReference().getName());
}
*/
}
if (transform_done) {
// System.out.println(getName() + " invoked " + i + " renderers");
AnimationControl control =
(AnimationControl) getControl(AnimationControl.class);
if (control != null) {
control.init();
}
synchronized (ControlVector) {
Enumeration controls = ControlVector.elements();
while(controls.hasMoreElements()) {
Control cont = (Control) controls.nextElement();
if (ValueControl.class.isInstance(cont)) {
((ValueControl) cont).init();
}
}
}
}
if (transform_done || any_exceptions) {
notifyListeners(DisplayEvent.TRANSFORM_DONE, 0, 0);
}
}
// clear tickFlag-s in Control-s
maps = tmap.elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
map.resetTicks();
}
} // end synchronized (mapslock)
} finally {
// System.out.println("DisplayImpl call setWaitFlag(false)");
displayRenderer.setWaitFlag(false);
}
}
|
diff --git a/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java b/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
index f9066f7..f66341c 100644
--- a/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
+++ b/core/src/qa/qcri/nadeef/core/datamodel/CleanPlan.java
@@ -1,272 +1,273 @@
/*
* Copyright (C) Qatar Computing Research Institute, 2013.
* All rights reserved.
*/
package qa.qcri.nadeef.core.datamodel;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import qa.qcri.nadeef.core.exception.InvalidCleanPlanException;
import qa.qcri.nadeef.core.exception.InvalidRuleException;
import qa.qcri.nadeef.core.util.DBConnectionFactory;
import qa.qcri.nadeef.core.util.DBMetaDataTool;
import qa.qcri.nadeef.core.util.RuleBuilder;
import qa.qcri.nadeef.tools.*;
import java.io.File;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Nadeef cleaning plan.
*/
public class CleanPlan {
private DBConfig source;
private Rule rule;
private static Tracer tracer = Tracer.getTracer(CleanPlan.class);
// <editor-fold desc="Constructor">
/**
* Constructor.
*/
public CleanPlan(DBConfig sourceConfig, Rule rule) {
this.source = sourceConfig;
this.rule = rule;
}
// </editor-fold>
/**
* Creates a <code>CleanPlan</code> from JSON string.
*
* @param reader JSON string reader.
* @return <code>CleanPlan</code> object.
*/
@SuppressWarnings("unchecked")
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
- if (ex instanceof InvalidRuleException) {
+ ex.printStackTrace();
+ if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
// <editor-fold desc="Property Getters">
/**
* Gets the <code>DBConfig</code> for the clean source.
*
* @return <code>DBConfig</code>.
*/
public DBConfig getSourceDBConfig() {
return source;
}
/**
* Gets the rule.
*
* @return rule.
*/
public Rule getRule() {
return rule;
}
// </editor-fold>
}
| true | true | public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
| public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}
|
diff --git a/org.eclipse.egit.mylyn.ui/src/org/eclipse/egit/internal/mylyn/ui/commit/TaskReferenceFactory.java b/org.eclipse.egit.mylyn.ui/src/org/eclipse/egit/internal/mylyn/ui/commit/TaskReferenceFactory.java
index 4ae6c249..98b1d642 100644
--- a/org.eclipse.egit.mylyn.ui/src/org/eclipse/egit/internal/mylyn/ui/commit/TaskReferenceFactory.java
+++ b/org.eclipse.egit.mylyn.ui/src/org/eclipse/egit/internal/mylyn/ui/commit/TaskReferenceFactory.java
@@ -1,199 +1,201 @@
/*******************************************************************************
* Copyright (c) 2011 Benjamin Muskalla 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:
* Benjamin Muskalla <[email protected]> - initial API and implementation
* Ilya Ivanov <[email protected]> - task repository url resolving
*******************************************************************************/
package org.eclipse.egit.internal.mylyn.ui.commit;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.egit.core.Activator;
import org.eclipse.egit.internal.mylyn.ui.EGitMylynUI;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCommit;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.team.ui.LinkedTaskInfo;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.team.ui.AbstractTaskReference;
/**
* Adapter factory to bridge between Mylyn and EGit domain models.
*/
@SuppressWarnings("restriction")
public class TaskReferenceFactory implements IAdapterFactory {
private static final Class<?>[] ADAPTER_TYPES = new Class[] { AbstractTaskReference.class };
private static final String BUGTRACK_SECTION = "bugtracker"; //$NON-NLS-1$
private static final String BUGTRACK_URL = "url"; //$NON-NLS-1$
@SuppressWarnings({ "rawtypes" })
public Class[] getAdapterList() {
return ADAPTER_TYPES;
}
@SuppressWarnings("rawtypes")
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (!AbstractTaskReference.class.equals(adapterType))
return null;
return adaptFromObject(adaptableObject);
}
private AbstractTaskReference adaptFromObject(Object element) {
RevCommit commit = getCommitForElement(element);
if (commit != null)
return adaptFromRevCommit(commit);
return null;
}
/**
* Finds {@link TaskRepository} for provided {@link RevCommit} object and returns new {@link LinkedTaskInfo} object
* or <code>null</code> if nothing found.
* @param commit a {@link RevCommit} object to look for
* @return {@link LinkedTaskInfo} object, or <code>null</code> if repository not found
*/
private AbstractTaskReference adaptFromRevCommit(RevCommit commit) {
Repository[] repositories = Activator.getDefault().getRepositoryCache().getAllRepositories();
for (Repository r : repositories) {
RevWalk revWalk = new RevWalk(r);
String repoUrl = null;
String message = null;
+ long timestamp = 0;
// try to get repository url and commit message
try {
RevCommit revCommit = revWalk.parseCommit(commit);
if (revCommit != null) {
repoUrl = getRepoUrl(r);
message = revCommit.getFullMessage();
+ timestamp = (long)revCommit.getCommitTime() * 1000;
}
} catch (Exception e) {
continue;
}
if (message == null || message.trim().length() == 0)
continue;
String taskRepositoryUrl = null;
if (repoUrl != null) {
TaskRepository repository = getTaskRepositoryByGitRepoURL(repoUrl);
if (repository != null)
taskRepositoryUrl = repository.getRepositoryUrl();
}
- return new LinkedTaskInfo(taskRepositoryUrl, null, null, message);
+ return new LinkedTaskInfo(taskRepositoryUrl, null, null, message, timestamp);
}
return null;
}
private static RevCommit getCommitForElement(Object element) {
RevCommit commit = null;
if (element instanceof RevCommit)
commit = (RevCommit) element;
else if (element instanceof GitModelCommit) {
GitModelCommit modelCommit = (GitModelCommit) element;
commit = modelCommit.getBaseCommit();
}
return commit;
}
/**
* Finds {@link TaskRepository} by provided Git repository Url
* @param repoUrl Git repository url
* @return {@link TaskRepository} associated with this Git repo or <code>null</code> if nothing found
*/
private TaskRepository getTaskRepositoryByGitRepoURL(final String repoUrl) {
if (repoUrl == null)
return null;
try {
return getTaskRepositoryByHost(new URIish(repoUrl).getHost());
} catch (Exception ex) {
EGitMylynUI.getDefault().getLog().log(
new Status(IStatus.ERROR, EGitMylynUI.PLUGIN_ID, "failed to get repo url", ex)); //$NON-NLS-1$
}
return null;
}
private static String getRepoUrl(Repository repo) {
String configuredUrl = repo.getConfig().getString(BUGTRACK_SECTION, null, BUGTRACK_URL);
String originUrl = repo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION,
Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL);
return configuredUrl != null ? configuredUrl : originUrl;
}
private TaskRepository getTaskRepositoryByHost(String host) {
List<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getAllRepositories();
if (repositories == null || repositories.isEmpty())
return null;
if (repositories.size() == 1)
return repositories.iterator().next();
for (TaskRepository repository : repositories) {
if (!repository.isOffline()) {
try {
URL url = new URL(repository.getRepositoryUrl());
if (isSameHosts(host, url.getHost()))
return repository;
} catch (MalformedURLException e) {
// We cannot do anything.
}
}
}
return null;
}
private boolean isSameHosts(final String name1, final String name2) {
String hostname1 = name1 == null ? "" : name1.trim(); //$NON-NLS-1$
String hostname2 = name2 == null ? "" : name2.trim(); //$NON-NLS-1$
if (hostname1.equals(hostname2))
return true;
String localHost = "localhost"; //$NON-NLS-1$
String resolvedHostName;
try {
resolvedHostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException ex) {
resolvedHostName = localHost;
}
if (hostname1.length() == 0)
hostname1 = resolvedHostName;
if (hostname2.length() == 0)
hostname2 = resolvedHostName;
if (hostname1.equals(hostname2))
return true;
if ((hostname1.equals(localHost) && hostname2.equals(resolvedHostName))
|| (hostname1.equals(resolvedHostName) && hostname2.equals(localHost)))
return true;
return false;
}
}
| false | true | private AbstractTaskReference adaptFromRevCommit(RevCommit commit) {
Repository[] repositories = Activator.getDefault().getRepositoryCache().getAllRepositories();
for (Repository r : repositories) {
RevWalk revWalk = new RevWalk(r);
String repoUrl = null;
String message = null;
// try to get repository url and commit message
try {
RevCommit revCommit = revWalk.parseCommit(commit);
if (revCommit != null) {
repoUrl = getRepoUrl(r);
message = revCommit.getFullMessage();
}
} catch (Exception e) {
continue;
}
if (message == null || message.trim().length() == 0)
continue;
String taskRepositoryUrl = null;
if (repoUrl != null) {
TaskRepository repository = getTaskRepositoryByGitRepoURL(repoUrl);
if (repository != null)
taskRepositoryUrl = repository.getRepositoryUrl();
}
return new LinkedTaskInfo(taskRepositoryUrl, null, null, message);
}
return null;
}
| private AbstractTaskReference adaptFromRevCommit(RevCommit commit) {
Repository[] repositories = Activator.getDefault().getRepositoryCache().getAllRepositories();
for (Repository r : repositories) {
RevWalk revWalk = new RevWalk(r);
String repoUrl = null;
String message = null;
long timestamp = 0;
// try to get repository url and commit message
try {
RevCommit revCommit = revWalk.parseCommit(commit);
if (revCommit != null) {
repoUrl = getRepoUrl(r);
message = revCommit.getFullMessage();
timestamp = (long)revCommit.getCommitTime() * 1000;
}
} catch (Exception e) {
continue;
}
if (message == null || message.trim().length() == 0)
continue;
String taskRepositoryUrl = null;
if (repoUrl != null) {
TaskRepository repository = getTaskRepositoryByGitRepoURL(repoUrl);
if (repository != null)
taskRepositoryUrl = repository.getRepositoryUrl();
}
return new LinkedTaskInfo(taskRepositoryUrl, null, null, message, timestamp);
}
return null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.