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/deegree-tools/src/main/java/org/deegree/tools/crs/XMLCoordinateTransform.java b/deegree-tools/src/main/java/org/deegree/tools/crs/XMLCoordinateTransform.java
index bdc253db49..b12ae972e3 100644
--- a/deegree-tools/src/main/java/org/deegree/tools/crs/XMLCoordinateTransform.java
+++ b/deegree-tools/src/main/java/org/deegree/tools/crs/XMLCoordinateTransform.java
@@ -1,234 +1,234 @@
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.tools.crs;
import static org.deegree.tools.CommandUtils.OPT_VERBOSE;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.deegree.commons.xml.stax.FormattingXMLStreamWriter;
import org.deegree.cs.CRS;
import org.deegree.cs.CRSRegistry;
import org.deegree.cs.coordinatesystems.CoordinateSystem;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.cs.transformations.Transformation;
import org.deegree.gml.GMLVersion;
import org.deegree.gml.XMLTransformer;
import org.deegree.tools.CommandUtils;
import org.deegree.tools.annotations.Tool;
import org.slf4j.Logger;
/**
* Tool for converting the GML geometries inside an XML document from one SRS to another.
*
* @author <a href="mailto:bezema@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@Tool("Converts the GML geometries inside an XML document from one SRS to another.")
public class XMLCoordinateTransform {
private static final Logger LOG = getLogger( XMLCoordinateTransform.class );
private static final String OPT_S_SRS = "source_srs";
private static final String OPT_T_SRS = "target_srs";
private static final String OPT_TRANSFORMATION = "transformation";
private static final String OPT_INPUT = "input";
private static final String OPT_GML_VERSION = "gml_version";
private static final String OPT_OUTPUT = "output";
/**
* a starter method to transform a given point or a serie of points read from a file.
*
* @param args
*/
public static void main( String[] args ) {
CommandLineParser parser = new PosixParser();
Options options = initOptions();
boolean verbose = false;
// for the moment, using the CLI API there is no way to respond to a help argument; see
// https://issues.apache.org/jira/browse/CLI-179
if ( args != null && args.length > 0 ) {
for ( String a : args ) {
if ( a != null && a.toLowerCase().contains( "help" ) || "-?".equals( a ) ) {
printHelp( options );
}
}
}
CommandLine line = null;
try {
line = parser.parse( options, args );
verbose = line.hasOption( OPT_VERBOSE );
doTransform( line );
} catch ( ParseException exp ) {
System.err.println( "ERROR: Invalid command line: " + exp.getMessage() );
printHelp( options );
} catch ( Throwable e ) {
System.err.println( "An Exception occurred while transforming your document, error message: "
+ e.getMessage() );
if ( verbose ) {
e.printStackTrace();
}
System.exit( 1 );
}
}
private static void doTransform( CommandLine line )
throws IllegalArgumentException, TransformationException, UnknownCRSException, IOException,
XMLStreamException, FactoryConfigurationError {
// TODO source srs should actually override all srsName attributes in document, not just be the default
CoordinateSystem sourceCRS = null;
String sourceCRSId = line.getOptionValue( OPT_S_SRS );
if ( sourceCRSId != null ) {
sourceCRS = new CRS( sourceCRSId ).getWrappedCRS();
}
String targetCRSId = line.getOptionValue( OPT_T_SRS );
CoordinateSystem targetCRS = new CRS( targetCRSId ).getWrappedCRS();
String transId = line.getOptionValue( OPT_TRANSFORMATION );
List<Transformation> trans = null;
if ( transId != null ) {
Transformation t = CRSRegistry.getTransformation( null, transId );
if ( t != null ) {
trans = Collections.singletonList( CRSRegistry.getTransformation( null, transId ) );
} else {
throw new IllegalArgumentException( "Specified transformation id '" + transId
+ "' does not exist in CRS database." );
}
}
GMLVersion gmlVersion = GMLVersion.GML_31;
String gmlVersionString = line.getOptionValue( OPT_GML_VERSION );
if ( gmlVersionString != null ) {
gmlVersion = GMLVersion.valueOf( gmlVersionString );
}
String i = line.getOptionValue( OPT_INPUT );
File inputFile = new File( i );
if ( !inputFile.exists() ) {
throw new IllegalArgumentException( "Input file '" + inputFile + "' does not exist." );
}
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileInputStream( inputFile ) );
String o = line.getOptionValue( OPT_OUTPUT );
XMLStreamWriter xmlWriter = null;
if ( o != null ) {
File outputFile = new File( o );
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( new FileOutputStream( outputFile ),
"UTF-8" );
} else {
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( System.out, "UTF-8" );
}
- xmlWriter = new FormattingXMLStreamWriter( xmlWriter, " ", true );
+ xmlWriter = new FormattingXMLStreamWriter( xmlWriter, " ", false );
xmlWriter.writeStartDocument( "UTF-8", "1.0" );
XMLTransformer transformer = new XMLTransformer( targetCRS );
transformer.transform( xmlReader, xmlWriter, sourceCRS, gmlVersion, false, trans );
xmlWriter.close();
}
private static Options initOptions() {
Options options = new Options();
Option option = new Option( OPT_S_SRS, true, "Identifier of the source srs, e.g. 'EPSG:4326'." );
option.setArgs( 1 );
options.addOption( option );
option = new Option( OPT_T_SRS, true, "Identifier of the target srs, e.g. 'EPSG:4326'." );
option.setArgs( 1 );
option.setRequired( true );
options.addOption( option );
option = new Option( OPT_TRANSFORMATION, true, "Identifier of the transformation to be used, e.g. 'EPSG:4326'." );
option.setArgs( 1 );
options.addOption( option );
option = new Option( OPT_INPUT, true, "Filename of the XML file to be transformed" );
option.setArgs( 1 );
option.setRequired( true );
options.addOption( option );
option = new Option( OPT_GML_VERSION, true,
"GML version (GML_2, GML_30, GML_31 or GML_32). Defaults to GML_31 if omitted." );
option.setArgs( 1 );
options.addOption( option );
option = new Option( OPT_OUTPUT, true, "Filename of the output file. If omitted, output is directed to console." );
option.setArgs( 1 );
options.addOption( option );
CommandUtils.addDefaultOptions( options );
return options;
}
private static void printHelp( Options options ) {
CommandUtils.printHelp( options, XMLCoordinateTransform.class.getCanonicalName(), null, null );
}
}
| true | true | private static void doTransform( CommandLine line )
throws IllegalArgumentException, TransformationException, UnknownCRSException, IOException,
XMLStreamException, FactoryConfigurationError {
// TODO source srs should actually override all srsName attributes in document, not just be the default
CoordinateSystem sourceCRS = null;
String sourceCRSId = line.getOptionValue( OPT_S_SRS );
if ( sourceCRSId != null ) {
sourceCRS = new CRS( sourceCRSId ).getWrappedCRS();
}
String targetCRSId = line.getOptionValue( OPT_T_SRS );
CoordinateSystem targetCRS = new CRS( targetCRSId ).getWrappedCRS();
String transId = line.getOptionValue( OPT_TRANSFORMATION );
List<Transformation> trans = null;
if ( transId != null ) {
Transformation t = CRSRegistry.getTransformation( null, transId );
if ( t != null ) {
trans = Collections.singletonList( CRSRegistry.getTransformation( null, transId ) );
} else {
throw new IllegalArgumentException( "Specified transformation id '" + transId
+ "' does not exist in CRS database." );
}
}
GMLVersion gmlVersion = GMLVersion.GML_31;
String gmlVersionString = line.getOptionValue( OPT_GML_VERSION );
if ( gmlVersionString != null ) {
gmlVersion = GMLVersion.valueOf( gmlVersionString );
}
String i = line.getOptionValue( OPT_INPUT );
File inputFile = new File( i );
if ( !inputFile.exists() ) {
throw new IllegalArgumentException( "Input file '" + inputFile + "' does not exist." );
}
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileInputStream( inputFile ) );
String o = line.getOptionValue( OPT_OUTPUT );
XMLStreamWriter xmlWriter = null;
if ( o != null ) {
File outputFile = new File( o );
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( new FileOutputStream( outputFile ),
"UTF-8" );
} else {
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( System.out, "UTF-8" );
}
xmlWriter = new FormattingXMLStreamWriter( xmlWriter, " ", true );
xmlWriter.writeStartDocument( "UTF-8", "1.0" );
XMLTransformer transformer = new XMLTransformer( targetCRS );
transformer.transform( xmlReader, xmlWriter, sourceCRS, gmlVersion, false, trans );
xmlWriter.close();
}
| private static void doTransform( CommandLine line )
throws IllegalArgumentException, TransformationException, UnknownCRSException, IOException,
XMLStreamException, FactoryConfigurationError {
// TODO source srs should actually override all srsName attributes in document, not just be the default
CoordinateSystem sourceCRS = null;
String sourceCRSId = line.getOptionValue( OPT_S_SRS );
if ( sourceCRSId != null ) {
sourceCRS = new CRS( sourceCRSId ).getWrappedCRS();
}
String targetCRSId = line.getOptionValue( OPT_T_SRS );
CoordinateSystem targetCRS = new CRS( targetCRSId ).getWrappedCRS();
String transId = line.getOptionValue( OPT_TRANSFORMATION );
List<Transformation> trans = null;
if ( transId != null ) {
Transformation t = CRSRegistry.getTransformation( null, transId );
if ( t != null ) {
trans = Collections.singletonList( CRSRegistry.getTransformation( null, transId ) );
} else {
throw new IllegalArgumentException( "Specified transformation id '" + transId
+ "' does not exist in CRS database." );
}
}
GMLVersion gmlVersion = GMLVersion.GML_31;
String gmlVersionString = line.getOptionValue( OPT_GML_VERSION );
if ( gmlVersionString != null ) {
gmlVersion = GMLVersion.valueOf( gmlVersionString );
}
String i = line.getOptionValue( OPT_INPUT );
File inputFile = new File( i );
if ( !inputFile.exists() ) {
throw new IllegalArgumentException( "Input file '" + inputFile + "' does not exist." );
}
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(
new FileInputStream( inputFile ) );
String o = line.getOptionValue( OPT_OUTPUT );
XMLStreamWriter xmlWriter = null;
if ( o != null ) {
File outputFile = new File( o );
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( new FileOutputStream( outputFile ),
"UTF-8" );
} else {
xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( System.out, "UTF-8" );
}
xmlWriter = new FormattingXMLStreamWriter( xmlWriter, " ", false );
xmlWriter.writeStartDocument( "UTF-8", "1.0" );
XMLTransformer transformer = new XMLTransformer( targetCRS );
transformer.transform( xmlReader, xmlWriter, sourceCRS, gmlVersion, false, trans );
xmlWriter.close();
}
|
diff --git a/src/driver/GUIDriver.java b/src/driver/GUIDriver.java
index 67f4da5..e975559 100644
--- a/src/driver/GUIDriver.java
+++ b/src/driver/GUIDriver.java
@@ -1,309 +1,309 @@
package driver;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFrame;
import world.Character;
import world.Enemy;
import world.Grid;
import world.GridSpace;
import world.LivingThing;
import world.Terrain;
import world.Thing;
import world.World;
public class GUIDriver {
private static Grid g;
private static long gravityRate;
private static int lastKey;
private static long hangTime;
private static long value;
private static boolean spaceDown = false;
private static int stage = 1;
public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
g = new Grid(0);
g.makeDefaultGrid();
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
g.retractWeapon(lastKey);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_A;
} else if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_D;
} else if (keyCode == KeyEvent.VK_SPACE) {
if (!spaceDown) {
spaceDown = true;
g.useWeapon(lastKey);
}
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color c = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10));
} else {
System.out.println("Could not spawn a new enemy.");
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_SPACE) {
g.retractWeapon(lastKey);
spaceDown = false;
}
}
});
while (true) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.moveRangedWeapon();
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0);
} else {
g.moveEnemy(1, 0);
}
- if (true) {
+ if (p.equals(g.getEnemyLocation().get(i))) {
if (gs.returnThings().size() > 0) {
if (gs.hasSolid()) {
if (gs.returnWeapons().size() == 0) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
} else {
for (LivingThing e : gs.returnLivingThings()) {
if (e.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
for (Terrain t : gs.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
}
}
}
}
g.moveEnemy(0, 1);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
}
if (enemyDamageTime > 500) {
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(0, (int) oldLocation.getY()), gs);
g.setCharacterLocation(new Point(0, (int) oldLocation.getY()));
}
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
try {
switch (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getHp()) {
case 20:
g2d.drawString("Health: * * * *", 320, 20);
break;
case 15:
g2d.drawString("Health: * * * _", 320, 20);
break;
case 10:
g2d.drawString("Health: * * _ _", 320, 20);
break;
case 5:
g2d.drawString("Health: * _ _ _", 320, 20);
break;
default:
g2d.drawString("Health: _ _ _ _", 320, 20);
break;
}
} catch (NullPointerException e) {
System.out.println("Caught that error");
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
}
| true | true | public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
g = new Grid(0);
g.makeDefaultGrid();
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
g.retractWeapon(lastKey);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_A;
} else if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_D;
} else if (keyCode == KeyEvent.VK_SPACE) {
if (!spaceDown) {
spaceDown = true;
g.useWeapon(lastKey);
}
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color c = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10));
} else {
System.out.println("Could not spawn a new enemy.");
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_SPACE) {
g.retractWeapon(lastKey);
spaceDown = false;
}
}
});
while (true) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.moveRangedWeapon();
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0);
} else {
g.moveEnemy(1, 0);
}
if (true) {
if (gs.returnThings().size() > 0) {
if (gs.hasSolid()) {
if (gs.returnWeapons().size() == 0) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
} else {
for (LivingThing e : gs.returnLivingThings()) {
if (e.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
for (Terrain t : gs.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
}
}
}
}
g.moveEnemy(0, 1);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
}
if (enemyDamageTime > 500) {
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(0, (int) oldLocation.getY()), gs);
g.setCharacterLocation(new Point(0, (int) oldLocation.getY()));
}
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
try {
switch (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getHp()) {
case 20:
g2d.drawString("Health: * * * *", 320, 20);
break;
case 15:
g2d.drawString("Health: * * * _", 320, 20);
break;
case 10:
g2d.drawString("Health: * * _ _", 320, 20);
break;
case 5:
g2d.drawString("Health: * _ _ _", 320, 20);
break;
default:
g2d.drawString("Health: _ _ _ _", 320, 20);
break;
}
} catch (NullPointerException e) {
System.out.println("Caught that error");
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
| public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
g = new Grid(0);
g.makeDefaultGrid();
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
g.retractWeapon(lastKey);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_A;
} else if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_D;
} else if (keyCode == KeyEvent.VK_SPACE) {
if (!spaceDown) {
spaceDown = true;
g.useWeapon(lastKey);
}
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color c = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10));
} else {
System.out.println("Could not spawn a new enemy.");
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_SPACE) {
g.retractWeapon(lastKey);
spaceDown = false;
}
}
});
while (true) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.moveRangedWeapon();
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0);
} else {
g.moveEnemy(1, 0);
}
if (p.equals(g.getEnemyLocation().get(i))) {
if (gs.returnThings().size() > 0) {
if (gs.hasSolid()) {
if (gs.returnWeapons().size() == 0) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
} else {
for (LivingThing e : gs.returnLivingThings()) {
if (e.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
for (Terrain t : gs.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
g.moveEnemy(0, -1);
}
}
}
}
}
}
g.moveEnemy(0, 1);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
}
if (enemyDamageTime > 500) {
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(0, (int) oldLocation.getY()), gs);
g.setCharacterLocation(new Point(0, (int) oldLocation.getY()));
}
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
try {
switch (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getHp()) {
case 20:
g2d.drawString("Health: * * * *", 320, 20);
break;
case 15:
g2d.drawString("Health: * * * _", 320, 20);
break;
case 10:
g2d.drawString("Health: * * _ _", 320, 20);
break;
case 5:
g2d.drawString("Health: * _ _ _", 320, 20);
break;
default:
g2d.drawString("Health: _ _ _ _", 320, 20);
break;
}
} catch (NullPointerException e) {
System.out.println("Caught that error");
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
|
diff --git a/src/main/java/com/gitblit/wicket/WicketUtils.java b/src/main/java/com/gitblit/wicket/WicketUtils.java
index e4eb29fb..6e03032e 100644
--- a/src/main/java/com/gitblit/wicket/WicketUtils.java
+++ b/src/main/java/com/gitblit/wicket/WicketUtils.java
@@ -1,601 +1,601 @@
/*
* Copyright 2011 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.wicket;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.Component;
import org.apache.wicket.PageParameters;
import org.apache.wicket.Request;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.ContextImage;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.resource.ContextRelativeResource;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.wicketstuff.googlecharts.AbstractChartData;
import org.wicketstuff.googlecharts.IChartData;
import com.gitblit.Constants;
import com.gitblit.Constants.FederationPullStatus;
import com.gitblit.GitBlit;
import com.gitblit.Keys;
import com.gitblit.models.FederationModel;
import com.gitblit.models.Metric;
import com.gitblit.utils.HttpUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
public class WicketUtils {
public static void setCssClass(Component container, String value) {
container.add(new SimpleAttributeModifier("class", value));
}
public static void setCssStyle(Component container, String value) {
container.add(new SimpleAttributeModifier("style", value));
}
public static void setCssBackground(Component container, String value) {
String background = MessageFormat.format("background-color:{0};",
StringUtils.getColor(value));
container.add(new SimpleAttributeModifier("style", background));
}
public static void setHtmlTooltip(Component container, String value) {
container.add(new SimpleAttributeModifier("title", value));
}
public static void setInputPlaceholder(Component container, String value) {
container.add(new SimpleAttributeModifier("placeholder", value));
}
public static void setChangeTypeCssClass(Component container, ChangeType type) {
switch (type) {
case ADD:
setCssClass(container, "addition");
break;
case COPY:
case RENAME:
setCssClass(container, "rename");
break;
case DELETE:
setCssClass(container, "deletion");
break;
case MODIFY:
setCssClass(container, "modification");
break;
}
}
public static void setTicketCssClass(Component container, String state) {
String css = null;
if (state.equals("open")) {
css = "label label-important";
} else if (state.equals("hold")) {
css = "label label-warning";
} else if (state.equals("resolved")) {
css = "label label-success";
} else if (state.equals("invalid")) {
css = "label";
}
if (css != null) {
setCssClass(container, css);
}
}
public static void setAlternatingBackground(Component c, int i) {
String clazz = i % 2 == 0 ? "light" : "dark";
setCssClass(c, clazz);
}
public static Label createAuthorLabel(String wicketId, String author) {
Label label = new Label(wicketId, author);
WicketUtils.setHtmlTooltip(label, author);
return label;
}
public static ContextImage getPullStatusImage(String wicketId, FederationPullStatus status) {
String filename = null;
switch (status) {
case MIRRORED:
case PULLED:
filename = "bullet_green.png";
break;
case SKIPPED:
filename = "bullet_yellow.png";
break;
case FAILED:
filename = "bullet_red.png";
break;
case EXCLUDED:
filename = "bullet_white.png";
break;
case PENDING:
case NOCHANGE:
default:
filename = "bullet_black.png";
}
return WicketUtils.newImage(wicketId, filename, status.name());
}
public static ContextImage getFileImage(String wicketId, String filename) {
filename = filename.toLowerCase();
if (filename.endsWith(".java")) {
return newImage(wicketId, "file_java_16x16.png");
} else if (filename.endsWith(".rb")) {
return newImage(wicketId, "file_ruby_16x16.png");
} else if (filename.endsWith(".php")) {
return newImage(wicketId, "file_php_16x16.png");
} else if (filename.endsWith(".cs")) {
return newImage(wicketId, "file_cs_16x16.png");
} else if (filename.endsWith(".cpp")) {
return newImage(wicketId, "file_cpp_16x16.png");
} else if (filename.endsWith(".c")) {
return newImage(wicketId, "file_c_16x16.png");
} else if (filename.endsWith(".h")) {
return newImage(wicketId, "file_h_16x16.png");
} else if (filename.endsWith(".sln")) {
return newImage(wicketId, "file_vs_16x16.png");
} else if (filename.endsWith(".csv") || filename.endsWith(".xls")
|| filename.endsWith(".xlsx")) {
return newImage(wicketId, "file_excel_16x16.png");
} else if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
- return newImage(wicketId, "file_word_16x16.png");
+ return newImage(wicketId, "file_doc_16x16.png");
} else if (filename.endsWith(".ppt")) {
return newImage(wicketId, "file_ppt_16x16.png");
} else if (filename.endsWith(".zip")) {
return newImage(wicketId, "file_zip_16x16.png");
} else if (filename.endsWith(".pdf")) {
return newImage(wicketId, "file_acrobat_16x16.png");
} else if (filename.endsWith(".htm") || filename.endsWith(".html")) {
return newImage(wicketId, "file_world_16x16.png");
} else if (filename.endsWith(".xml")) {
return newImage(wicketId, "file_code_16x16.png");
} else if (filename.endsWith(".properties")) {
return newImage(wicketId, "file_settings_16x16.png");
}
List<String> mdExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
for (String ext : mdExtensions) {
if (filename.endsWith('.' + ext.toLowerCase())) {
return newImage(wicketId, "file_world_16x16.png");
}
}
return newImage(wicketId, "file_16x16.png");
}
public static ContextImage getRegistrationImage(String wicketId, FederationModel registration,
Component c) {
if (registration.isResultData()) {
return WicketUtils.newImage(wicketId, "information_16x16.png",
c.getString("gb.federationResults"));
} else {
return WicketUtils.newImage(wicketId, "arrow_left.png",
c.getString("gb.federationRegistration"));
}
}
public static ContextImage newClearPixel(String wicketId) {
return newImage(wicketId, "pixel.png");
}
public static ContextImage newBlankImage(String wicketId) {
return newImage(wicketId, "blank.png");
}
public static ContextImage newImage(String wicketId, String file) {
return newImage(wicketId, file, null);
}
public static ContextImage newImage(String wicketId, String file, String tooltip) {
ContextImage img = new ContextImage(wicketId, file);
if (!StringUtils.isEmpty(tooltip)) {
setHtmlTooltip(img, tooltip);
}
return img;
}
public static Label newIcon(String wicketId, String css) {
Label lbl = new Label(wicketId);
setCssClass(lbl, css);
return lbl;
}
public static Label newBlankIcon(String wicketId) {
Label lbl = new Label(wicketId);
setCssClass(lbl, "");
lbl.setRenderBodyOnly(true);
return lbl;
}
public static ContextRelativeResource getResource(String file) {
return new ContextRelativeResource(file);
}
public static String getGitblitURL(Request request) {
HttpServletRequest req = ((WebRequest) request).getHttpServletRequest();
return HttpUtils.getGitblitURL(req);
}
public static HeaderContributor syndicationDiscoveryLink(final String feedTitle,
final String url) {
return new HeaderContributor(new IHeaderContributor() {
private static final long serialVersionUID = 1L;
public void renderHead(IHeaderResponse response) {
String contentType = "application/rss+xml";
StringBuilder buffer = new StringBuilder();
buffer.append("<link rel=\"alternate\" ");
buffer.append("type=\"").append(contentType).append("\" ");
buffer.append("title=\"").append(feedTitle).append("\" ");
buffer.append("href=\"").append(url).append("\" />");
response.renderString(buffer.toString());
}
});
}
public static PageParameters newTokenParameter(String token) {
return new PageParameters("t=" + token);
}
public static PageParameters newRegistrationParameter(String url, String name) {
return new PageParameters("u=" + url + ",n=" + name);
}
public static PageParameters newUsernameParameter(String username) {
return new PageParameters("user=" + username);
}
public static PageParameters newTeamnameParameter(String teamname) {
return new PageParameters("team=" + teamname);
}
public static PageParameters newProjectParameter(String projectName) {
return new PageParameters("p=" + projectName);
}
public static PageParameters newRepositoryParameter(String repositoryName) {
return new PageParameters("r=" + repositoryName);
}
public static PageParameters newObjectParameter(String objectId) {
return new PageParameters("h=" + objectId);
}
public static PageParameters newObjectParameter(String repositoryName, String objectId) {
if (StringUtils.isEmpty(objectId)) {
return newRepositoryParameter(repositoryName);
}
return new PageParameters("r=" + repositoryName + ",h=" + objectId);
}
public static PageParameters newPathParameter(String repositoryName, String objectId,
String path) {
if (StringUtils.isEmpty(path)) {
return newObjectParameter(repositoryName, objectId);
}
if (StringUtils.isEmpty(objectId)) {
return new PageParameters("r=" + repositoryName + ",f=" + path);
}
return new PageParameters("r=" + repositoryName + ",h=" + objectId + ",f=" + path);
}
public static PageParameters newLogPageParameter(String repositoryName, String objectId,
int pageNumber) {
if (pageNumber <= 1) {
return newObjectParameter(repositoryName, objectId);
}
if (StringUtils.isEmpty(objectId)) {
return new PageParameters("r=" + repositoryName + ",pg=" + pageNumber);
}
return new PageParameters("r=" + repositoryName + ",h=" + objectId + ",pg=" + pageNumber);
}
public static PageParameters newHistoryPageParameter(String repositoryName, String objectId,
String path, int pageNumber) {
if (pageNumber <= 1) {
return newObjectParameter(repositoryName, objectId);
}
if (StringUtils.isEmpty(objectId)) {
return new PageParameters("r=" + repositoryName + ",f=" + path + ",pg=" + pageNumber);
}
return new PageParameters("r=" + repositoryName + ",h=" + objectId + ",f=" + path + ",pg="
+ pageNumber);
}
public static PageParameters newBlobDiffParameter(String repositoryName, String baseCommitId,
String commitId, String path) {
if (StringUtils.isEmpty(commitId)) {
return new PageParameters("r=" + repositoryName + ",f=" + path + ",hb=" + baseCommitId);
}
return new PageParameters("r=" + repositoryName + ",h=" + commitId + ",f=" + path + ",hb="
+ baseCommitId);
}
public static PageParameters newSearchParameter(String repositoryName, String commitId,
String search, Constants.SearchType type) {
if (StringUtils.isEmpty(commitId)) {
return new PageParameters("r=" + repositoryName + ",s=" + search + ",st=" + type.name());
}
return new PageParameters("r=" + repositoryName + ",h=" + commitId + ",s=" + search
+ ",st=" + type.name());
}
public static PageParameters newSearchParameter(String repositoryName, String commitId,
String search, Constants.SearchType type, int pageNumber) {
if (StringUtils.isEmpty(commitId)) {
return new PageParameters("r=" + repositoryName + ",s=" + search + ",st=" + type.name()
+ ",pg=" + pageNumber);
}
return new PageParameters("r=" + repositoryName + ",h=" + commitId + ",s=" + search
+ ",st=" + type.name() + ",pg=" + pageNumber);
}
public static String getProjectName(PageParameters params) {
return params.getString("p", "");
}
public static String getRepositoryName(PageParameters params) {
return params.getString("r", "");
}
public static String getObject(PageParameters params) {
return params.getString("h", null);
}
public static String getPath(PageParameters params) {
return params.getString("f", null);
}
public static String getBaseObjectId(PageParameters params) {
return params.getString("hb", null);
}
public static String getSearchString(PageParameters params) {
return params.getString("s", null);
}
public static String getSearchType(PageParameters params) {
return params.getString("st", null);
}
public static int getPage(PageParameters params) {
// index from 1
return params.getInt("pg", 1);
}
public static String getRegEx(PageParameters params) {
return params.getString("x", "");
}
public static String getSet(PageParameters params) {
return params.getString("set", "");
}
public static String getTeam(PageParameters params) {
return params.getString("team", "");
}
public static int getDaysBack(PageParameters params) {
return params.getInt("db", 14);
}
public static String getUsername(PageParameters params) {
return params.getString("user", "");
}
public static String getTeamname(PageParameters params) {
return params.getString("team", "");
}
public static String getToken(PageParameters params) {
return params.getString("t", "");
}
public static String getUrlParameter(PageParameters params) {
return params.getString("u", "");
}
public static String getNameParameter(PageParameters params) {
return params.getString("n", "");
}
public static Label createDateLabel(String wicketId, Date date, TimeZone timeZone, TimeUtils timeUtils) {
String format = GitBlit.getString(Keys.web.datestampShortFormat, "MM/dd/yy");
DateFormat df = new SimpleDateFormat(format);
if (timeZone == null) {
timeZone = GitBlit.getTimezone();
}
df.setTimeZone(timeZone);
String dateString;
if (date.getTime() == 0) {
dateString = "--";
} else {
dateString = df.format(date);
}
String title = null;
if (date.getTime() <= System.currentTimeMillis()) {
// past
title = timeUtils.timeAgo(date);
}
if ((System.currentTimeMillis() - date.getTime()) < 10 * 24 * 60 * 60 * 1000L) {
String tmp = dateString;
dateString = title;
title = tmp;
}
Label label = new Label(wicketId, dateString);
WicketUtils.setCssClass(label, timeUtils.timeAgoCss(date));
if (!StringUtils.isEmpty(title)) {
WicketUtils.setHtmlTooltip(label, title);
}
return label;
}
public static Label createTimeLabel(String wicketId, Date date, TimeZone timeZone, TimeUtils timeUtils) {
String format = GitBlit.getString(Keys.web.timeFormat, "HH:mm");
DateFormat df = new SimpleDateFormat(format);
if (timeZone == null) {
timeZone = GitBlit.getTimezone();
}
df.setTimeZone(timeZone);
String timeString;
if (date.getTime() == 0) {
timeString = "--";
} else {
timeString = df.format(date);
}
String title = timeUtils.timeAgo(date);
Label label = new Label(wicketId, timeString);
if (!StringUtils.isEmpty(title)) {
WicketUtils.setHtmlTooltip(label, title);
}
return label;
}
public static Label createDatestampLabel(String wicketId, Date date, TimeZone timeZone, TimeUtils timeUtils) {
String format = GitBlit.getString(Keys.web.datestampLongFormat, "EEEE, MMMM d, yyyy");
DateFormat df = new SimpleDateFormat(format);
if (timeZone == null) {
timeZone = GitBlit.getTimezone();
}
df.setTimeZone(timeZone);
String dateString;
if (date.getTime() == 0) {
dateString = "--";
} else {
dateString = df.format(date);
}
String title = null;
if (TimeUtils.isToday(date)) {
title = timeUtils.today();
} else if (TimeUtils.isYesterday(date)) {
title = timeUtils.yesterday();
} else if (date.getTime() <= System.currentTimeMillis()) {
// past
title = timeUtils.timeAgo(date);
}
if ((System.currentTimeMillis() - date.getTime()) < 10 * 24 * 60 * 60 * 1000L) {
String tmp = dateString;
dateString = title;
title = tmp;
}
Label label = new Label(wicketId, dateString);
if (!StringUtils.isEmpty(title)) {
WicketUtils.setHtmlTooltip(label, title);
}
return label;
}
public static Label createTimestampLabel(String wicketId, Date date, TimeZone timeZone, TimeUtils timeUtils) {
String format = GitBlit.getString(Keys.web.datetimestampLongFormat,
"EEEE, MMMM d, yyyy HH:mm Z");
DateFormat df = new SimpleDateFormat(format);
if (timeZone == null) {
timeZone = GitBlit.getTimezone();
}
df.setTimeZone(timeZone);
String dateString;
if (date.getTime() == 0) {
dateString = "--";
} else {
dateString = df.format(date);
}
String title = null;
if (date.getTime() <= System.currentTimeMillis()) {
// past
title = timeUtils.timeAgo(date);
}
Label label = new Label(wicketId, dateString);
if (!StringUtils.isEmpty(title)) {
WicketUtils.setHtmlTooltip(label, title);
}
return label;
}
public static IChartData getChartData(Collection<Metric> metrics) {
final double[] commits = new double[metrics.size()];
final double[] tags = new double[metrics.size()];
int i = 0;
double max = 0;
for (Metric m : metrics) {
commits[i] = m.count;
if (m.tag > 0) {
tags[i] = m.count;
} else {
tags[i] = -1d;
}
max = Math.max(max, m.count);
i++;
}
IChartData data = new AbstractChartData(max) {
private static final long serialVersionUID = 1L;
public double[][] getData() {
return new double[][] { commits, tags };
}
};
return data;
}
public static double maxValue(Collection<Metric> metrics) {
double max = Double.MIN_VALUE;
for (Metric m : metrics) {
if (m.count > max) {
max = m.count;
}
}
return max;
}
public static IChartData getScatterData(Collection<Metric> metrics) {
final double[] y = new double[metrics.size()];
final double[] x = new double[metrics.size()];
int i = 0;
double max = 0;
for (Metric m : metrics) {
y[i] = m.count;
if (m.duration > 0) {
x[i] = m.duration;
} else {
x[i] = -1d;
}
max = Math.max(max, m.count);
i++;
}
IChartData data = new AbstractChartData(max) {
private static final long serialVersionUID = 1L;
public double[][] getData() {
return new double[][] { x, y };
}
};
return data;
}
}
| true | true | public static ContextImage getFileImage(String wicketId, String filename) {
filename = filename.toLowerCase();
if (filename.endsWith(".java")) {
return newImage(wicketId, "file_java_16x16.png");
} else if (filename.endsWith(".rb")) {
return newImage(wicketId, "file_ruby_16x16.png");
} else if (filename.endsWith(".php")) {
return newImage(wicketId, "file_php_16x16.png");
} else if (filename.endsWith(".cs")) {
return newImage(wicketId, "file_cs_16x16.png");
} else if (filename.endsWith(".cpp")) {
return newImage(wicketId, "file_cpp_16x16.png");
} else if (filename.endsWith(".c")) {
return newImage(wicketId, "file_c_16x16.png");
} else if (filename.endsWith(".h")) {
return newImage(wicketId, "file_h_16x16.png");
} else if (filename.endsWith(".sln")) {
return newImage(wicketId, "file_vs_16x16.png");
} else if (filename.endsWith(".csv") || filename.endsWith(".xls")
|| filename.endsWith(".xlsx")) {
return newImage(wicketId, "file_excel_16x16.png");
} else if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
return newImage(wicketId, "file_word_16x16.png");
} else if (filename.endsWith(".ppt")) {
return newImage(wicketId, "file_ppt_16x16.png");
} else if (filename.endsWith(".zip")) {
return newImage(wicketId, "file_zip_16x16.png");
} else if (filename.endsWith(".pdf")) {
return newImage(wicketId, "file_acrobat_16x16.png");
} else if (filename.endsWith(".htm") || filename.endsWith(".html")) {
return newImage(wicketId, "file_world_16x16.png");
} else if (filename.endsWith(".xml")) {
return newImage(wicketId, "file_code_16x16.png");
} else if (filename.endsWith(".properties")) {
return newImage(wicketId, "file_settings_16x16.png");
}
List<String> mdExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
for (String ext : mdExtensions) {
if (filename.endsWith('.' + ext.toLowerCase())) {
return newImage(wicketId, "file_world_16x16.png");
}
}
return newImage(wicketId, "file_16x16.png");
}
| public static ContextImage getFileImage(String wicketId, String filename) {
filename = filename.toLowerCase();
if (filename.endsWith(".java")) {
return newImage(wicketId, "file_java_16x16.png");
} else if (filename.endsWith(".rb")) {
return newImage(wicketId, "file_ruby_16x16.png");
} else if (filename.endsWith(".php")) {
return newImage(wicketId, "file_php_16x16.png");
} else if (filename.endsWith(".cs")) {
return newImage(wicketId, "file_cs_16x16.png");
} else if (filename.endsWith(".cpp")) {
return newImage(wicketId, "file_cpp_16x16.png");
} else if (filename.endsWith(".c")) {
return newImage(wicketId, "file_c_16x16.png");
} else if (filename.endsWith(".h")) {
return newImage(wicketId, "file_h_16x16.png");
} else if (filename.endsWith(".sln")) {
return newImage(wicketId, "file_vs_16x16.png");
} else if (filename.endsWith(".csv") || filename.endsWith(".xls")
|| filename.endsWith(".xlsx")) {
return newImage(wicketId, "file_excel_16x16.png");
} else if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
return newImage(wicketId, "file_doc_16x16.png");
} else if (filename.endsWith(".ppt")) {
return newImage(wicketId, "file_ppt_16x16.png");
} else if (filename.endsWith(".zip")) {
return newImage(wicketId, "file_zip_16x16.png");
} else if (filename.endsWith(".pdf")) {
return newImage(wicketId, "file_acrobat_16x16.png");
} else if (filename.endsWith(".htm") || filename.endsWith(".html")) {
return newImage(wicketId, "file_world_16x16.png");
} else if (filename.endsWith(".xml")) {
return newImage(wicketId, "file_code_16x16.png");
} else if (filename.endsWith(".properties")) {
return newImage(wicketId, "file_settings_16x16.png");
}
List<String> mdExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
for (String ext : mdExtensions) {
if (filename.endsWith('.' + ext.toLowerCase())) {
return newImage(wicketId, "file_world_16x16.png");
}
}
return newImage(wicketId, "file_16x16.png");
}
|
diff --git a/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java b/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
index 927ef2d..76d3d53 100755
--- a/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
+++ b/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
@@ -1,247 +1,249 @@
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package com.phonegap.plugins.sqlitePlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.database.Cursor;
import android.database.sqlite.*;
import android.util.Log;
public class SQLitePlugin extends Plugin {
// Data Definition Language
SQLiteDatabase myDb = null; // Database object
String path = null; // Database path
String dbName = null; // Database name
/**
* Constructor.
*/
public SQLitePlugin() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action
* The action to execute.
* @param args
* JSONArry of arguments for the plugin.
* @param callbackId
* The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
- queryIDs[i] = a.getString("query_id");
+ queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
+ if(params[i][j] == "null")
+ params[i][j] = "";
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run
* synchronously.
*
* @param action
* The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
return true;
}
/**
* Clean up and close database.
*/
@Override
public void onDestroy() {
if (this.myDb != null) {
this.myDb.close();
this.myDb = null;
}
}
// --------------------------------------------------------------------------
// LOCAL METHODS
// --------------------------------------------------------------------------
/**
* Set the application package for the database. Each application saves its
* database files in a directory with the application package as part of the
* file name.
*
* For example, application "com.phonegap.demo.Demo" would save its database
* files in "/data/data/com.phonegap.demo/databases/" directory.
*
* @param appPackage
* The application package.
*/
public void setStorage(String appPackage) {
this.path = "/data/data/" + appPackage + "/databases/";
}
/**
* Open database.
*
* @param db
* The name of the database
* @param version
* The version
* @param display_name
* The display name
* @param size
* The size in bytes
*/
public void openDatabase(String db, String version, String display_name,
long size) {
// If database is open, then close it
if (this.myDb != null) {
this.myDb.close();
}
// If no database path, generate from application package
if (this.path == null) {
Package pack = this.ctx.getClass().getPackage();
String appPackage = pack.getName();
this.setStorage(appPackage);
}
this.dbName = this.path + db + ".db";
this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null);
}
public void executeSqlBatch(String[] queryarr, String[][] paramsarr, String[] queryIDs, String tx_id) {
try {
this.myDb.beginTransaction();
String query = "";
String query_id = "";
String[] params;
int len = queryarr.length;
for (int i = 0; i < len; i++) {
query = queryarr[i];
params = paramsarr[i];
query_id = queryIDs[i];
Cursor myCursor = this.myDb.rawQuery(query, params);
if(query_id != "")
this.processResults(myCursor, query_id, tx_id);
myCursor.close();
}
this.myDb.setTransactionSuccessful();
}
catch (SQLiteException ex) {
ex.printStackTrace();
Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
this.sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");
}
finally {
this.myDb.endTransaction();
Log.v("executeSqlBatch", tx_id);
this.sendJavascript("SQLitePluginTransaction.txCompleteCallback('" + tx_id + "');");
}
}
/**
* Process query results.
*
* @param cur
* Cursor into query results
* @param tx_id
* Transaction id
*/
public void processResults(Cursor cur, String query_id, String tx_id) {
String result = "[]";
// If query result has rows
if (cur.moveToFirst()) {
JSONArray fullresult = new JSONArray();
String key = "";
String value = "";
int colCount = cur.getColumnCount();
// Build up JSON result object for each row
do {
JSONObject row = new JSONObject();
try {
for (int i = 0; i < colCount; ++i) {
key = cur.getColumnName(i);
value = cur.getString(i);
row.put(key, value);
}
fullresult.put(row);
} catch (JSONException e) {
e.printStackTrace();
}
} while (cur.moveToNext());
result = fullresult.toString();
}
this.sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");");
}
}
| false | true | public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
| public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
if(params[i][j] == "null")
params[i][j] = "";
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
|
diff --git a/src/minecraft/org/getspout/spout/gui/GenericLabel.java b/src/minecraft/org/getspout/spout/gui/GenericLabel.java
index 6b664979..da8404fa 100644
--- a/src/minecraft/org/getspout/spout/gui/GenericLabel.java
+++ b/src/minecraft/org/getspout/spout/gui/GenericLabel.java
@@ -1,158 +1,158 @@
package org.getspout.spout.gui;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.lwjgl.opengl.GL11;
import org.getspout.spout.client.SpoutClient;
import org.getspout.spout.packet.PacketUtil;
import net.minecraft.src.FontRenderer;
public class GenericLabel extends GenericWidget implements Label{
protected String text = "";
protected Align vAlign = Align.FIRST;
protected Align hAlign = Align.FIRST;
protected int hexColor = 0xFFFFFF;
protected boolean auto = true;
public GenericLabel(){
}
public int getVersion() {
return 2;
}
public GenericLabel(String text) {
this.text = text;
}
@Override
public WidgetType getType() {
return WidgetType.Label;
}
@Override
public int getNumBytes() {
return super.getNumBytes() + PacketUtil.getNumBytes(getText()) + 7;
}
@Override
public void readData(DataInputStream input) throws IOException {
super.readData(input);
this.setText(PacketUtil.readString(input));
this.setAlignX(Align.getAlign(input.readByte()));
this.setAlignY(Align.getAlign(input.readByte()));
this.setAuto(input.readBoolean());
this.setHexColor(input.readInt());
}
@Override
public void writeData(DataOutputStream output) throws IOException {
super.writeData(output);
PacketUtil.writeString(output, getText());
output.writeByte(hAlign.getId());
output.writeByte(vAlign.getId());
output.writeBoolean(getAuto());
output.writeInt(getHexColor());
}
@Override
public String getText() {
return text;
}
@Override
public Label setText(String text) {
this.text = text;
return this;
}
@Override
public boolean getAuto() {
return auto;
}
@Override
public Label setAuto(boolean auto) {
this.auto = auto;
return this;
}
@Override
public Align getAlignX() {
return hAlign;
}
@Override
public Align getAlignY() {
return vAlign;
}
@Override
public Label setAlignX(Align pos) {
this.hAlign = pos;
return this;
}
@Override
public Label setAlignY(Align pos) {
this.vAlign = pos;
return this;
}
@Override
public int getHexColor() {
return hexColor;
}
@Override
public Label setHexColor(int hex) {
hexColor = hex;
return this;
}
public void render() {
FontRenderer font = SpoutClient.getHandle().fontRenderer;
String lines[] = getText().split("\\n");
double swidth = 0;
for (int i = 0; i < lines.length; i++) {
swidth = font.getStringWidth(lines[i]) > swidth ? font.getStringWidth(lines[i]) : swidth;
}
double sheight = lines.length * 10;
double height = getHeight();
double width = getWidth();
double top = getScreenY();
switch (vAlign) {
case SECOND: top += (int) ((auto ? screen.getHeight() : height) / 2 - (auto ? (sheight * (screen.getHeight() / 240f)) : height) / 2); break;
case THIRD: top += (int) ((auto ? screen.getHeight() : height) - (auto ? (sheight * (screen.getHeight() / 240f)) : height)); break;
}
double aleft = getScreenX();
switch (hAlign) {
- case SECOND: aleft = ((auto ? screen.getWidth() : width) / 2) - ((auto ? (swidth * (screen.getWidth() / 427f)) : width) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
- case THIRD: aleft = (auto ? screen.getWidth() : width) - (auto ? (swidth * (screen.getWidth() / 427f)) : width); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
+ case SECOND: aleft += ((width) / 2) - ((auto ? (swidth * (screen.getWidth() / 427f)) : width) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
+ case THIRD: aleft += (width) - (auto ? (swidth * (screen.getWidth() / 427f)) : width); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
GL11.glPushMatrix();
GL11.glTranslatef((float) aleft, (float) top, 0);
if (auto) {
GL11.glScalef((float) (screen.getWidth() / 427f), (float) (screen.getHeight() / 240f), 1);
} else {
GL11.glScalef((float) (getWidth() / swidth), (float) (getHeight() / sheight), 1);
}
for (int i = 0; i < lines.length; i++) {
double left = 0;
switch (hAlign) {
case SECOND: left = (swidth / 2) - (font.getStringWidth(lines[i]) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
case THIRD: left = swidth - font.getStringWidth(lines[i]); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
font.drawStringWithShadow(lines[i], (int) left, i * 10, getHexColor());
}
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
}
| true | true | public void render() {
FontRenderer font = SpoutClient.getHandle().fontRenderer;
String lines[] = getText().split("\\n");
double swidth = 0;
for (int i = 0; i < lines.length; i++) {
swidth = font.getStringWidth(lines[i]) > swidth ? font.getStringWidth(lines[i]) : swidth;
}
double sheight = lines.length * 10;
double height = getHeight();
double width = getWidth();
double top = getScreenY();
switch (vAlign) {
case SECOND: top += (int) ((auto ? screen.getHeight() : height) / 2 - (auto ? (sheight * (screen.getHeight() / 240f)) : height) / 2); break;
case THIRD: top += (int) ((auto ? screen.getHeight() : height) - (auto ? (sheight * (screen.getHeight() / 240f)) : height)); break;
}
double aleft = getScreenX();
switch (hAlign) {
case SECOND: aleft = ((auto ? screen.getWidth() : width) / 2) - ((auto ? (swidth * (screen.getWidth() / 427f)) : width) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
case THIRD: aleft = (auto ? screen.getWidth() : width) - (auto ? (swidth * (screen.getWidth() / 427f)) : width); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
GL11.glPushMatrix();
GL11.glTranslatef((float) aleft, (float) top, 0);
if (auto) {
GL11.glScalef((float) (screen.getWidth() / 427f), (float) (screen.getHeight() / 240f), 1);
} else {
GL11.glScalef((float) (getWidth() / swidth), (float) (getHeight() / sheight), 1);
}
for (int i = 0; i < lines.length; i++) {
double left = 0;
switch (hAlign) {
case SECOND: left = (swidth / 2) - (font.getStringWidth(lines[i]) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
case THIRD: left = swidth - font.getStringWidth(lines[i]); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
font.drawStringWithShadow(lines[i], (int) left, i * 10, getHexColor());
}
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
| public void render() {
FontRenderer font = SpoutClient.getHandle().fontRenderer;
String lines[] = getText().split("\\n");
double swidth = 0;
for (int i = 0; i < lines.length; i++) {
swidth = font.getStringWidth(lines[i]) > swidth ? font.getStringWidth(lines[i]) : swidth;
}
double sheight = lines.length * 10;
double height = getHeight();
double width = getWidth();
double top = getScreenY();
switch (vAlign) {
case SECOND: top += (int) ((auto ? screen.getHeight() : height) / 2 - (auto ? (sheight * (screen.getHeight() / 240f)) : height) / 2); break;
case THIRD: top += (int) ((auto ? screen.getHeight() : height) - (auto ? (sheight * (screen.getHeight() / 240f)) : height)); break;
}
double aleft = getScreenX();
switch (hAlign) {
case SECOND: aleft += ((width) / 2) - ((auto ? (swidth * (screen.getWidth() / 427f)) : width) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
case THIRD: aleft += (width) - (auto ? (swidth * (screen.getWidth() / 427f)) : width); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
GL11.glPushMatrix();
GL11.glTranslatef((float) aleft, (float) top, 0);
if (auto) {
GL11.glScalef((float) (screen.getWidth() / 427f), (float) (screen.getHeight() / 240f), 1);
} else {
GL11.glScalef((float) (getWidth() / swidth), (float) (getHeight() / sheight), 1);
}
for (int i = 0; i < lines.length; i++) {
double left = 0;
switch (hAlign) {
case SECOND: left = (swidth / 2) - (font.getStringWidth(lines[i]) / 2); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 854f; break;
case THIRD: left = swidth - font.getStringWidth(lines[i]); break;// - (font.getStringWidth(lines[i]) * getScreen().getWidth()) / 427f; break;
}
font.drawStringWithShadow(lines[i], (int) left, i * 10, getHexColor());
}
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
|
diff --git a/nexus/nexus-utils/src/main/java/org/sonatype/nexus/util/ClasspathUtils.java b/nexus/nexus-utils/src/main/java/org/sonatype/nexus/util/ClasspathUtils.java
index c803224ed..3d7afb280 100644
--- a/nexus/nexus-utils/src/main/java/org/sonatype/nexus/util/ClasspathUtils.java
+++ b/nexus/nexus-utils/src/main/java/org/sonatype/nexus/util/ClasspathUtils.java
@@ -1,41 +1,43 @@
package org.sonatype.nexus.util;
/**
* Some classpath related utility methods.
*
* @author cstamas
*/
public class ClasspathUtils
{
/**
* Converts a supplied "binary name" into "canonical name" if possible. If not possible, returns null.
*
* @param binaryName to convert
* @return canonical name (in case of classes), null if conversion is not possible.
*/
public static String convertClassBinaryNameToCanonicalName( String binaryName )
{
// sanity check
if ( binaryName == null || binaryName.trim().length() == 0 )
{
return null;
}
if ( binaryName.endsWith( ".class" ) )
{
int startIdx = 0;
if ( binaryName.startsWith( "/" ) )
{
startIdx = 1;
}
// class name without ".class"
- return binaryName.substring( startIdx, binaryName.length() - 6 ).replace( "/", "." ); //.replace( "$", "." );
+ return binaryName.substring( startIdx, binaryName.length() - 6 ).
+ // replacing backslash to make windows happy
+ replace( '\\', '.' ).replace( "/", "." ); // .replace( "$", "." );
}
else
{
return null;
}
}
}
| true | true | public static String convertClassBinaryNameToCanonicalName( String binaryName )
{
// sanity check
if ( binaryName == null || binaryName.trim().length() == 0 )
{
return null;
}
if ( binaryName.endsWith( ".class" ) )
{
int startIdx = 0;
if ( binaryName.startsWith( "/" ) )
{
startIdx = 1;
}
// class name without ".class"
return binaryName.substring( startIdx, binaryName.length() - 6 ).replace( "/", "." ); //.replace( "$", "." );
}
else
{
return null;
}
}
| public static String convertClassBinaryNameToCanonicalName( String binaryName )
{
// sanity check
if ( binaryName == null || binaryName.trim().length() == 0 )
{
return null;
}
if ( binaryName.endsWith( ".class" ) )
{
int startIdx = 0;
if ( binaryName.startsWith( "/" ) )
{
startIdx = 1;
}
// class name without ".class"
return binaryName.substring( startIdx, binaryName.length() - 6 ).
// replacing backslash to make windows happy
replace( '\\', '.' ).replace( "/", "." ); // .replace( "$", "." );
}
else
{
return null;
}
}
|
diff --git a/test/models/ModelTest.java b/test/models/ModelTest.java
index acdf99c..748b304 100644
--- a/test/models/ModelTest.java
+++ b/test/models/ModelTest.java
@@ -1,47 +1,47 @@
package models;
import java.util.Date;
import models.Detail.COLOR;
import models.Detail.SIZE;
import org.junit.Test;
import play.test.UnitTest;
public class ModelTest extends UnitTest {
@Test
public void testClients(){
Client cl = new Client("Diego", "Ramirez");
assertNotNull(cl);
cl.save();
assertNotNull(Client.find("firstname", "Diego").first());
}
@Test
public void testOrderwithclient(){
Client cl = Client.find("firstname", "Diego").first();
assertNotNull(cl);
Order order = new Order( new Date(System.currentTimeMillis()) , cl);
assertNotNull(order);
order.save();
- Detail det = new Detail(COLOR.BLACK,SIZE.MEDIUM,2);
- Detail det2 = new Detail(COLOR.BLACK,SIZE.SMALL,3);
+ Detail det = new Detail(1,2,2);
+ Detail det2 = new Detail(1,2,3);
order.addDetail(det);
order.addDetail(det2);
order.save();
Payment pay = new Payment(new Date(System.currentTimeMillis()), 58.84F);
order.addPayment(pay);
assertTrue(order.payments.size()>0);
order.save();
}
}
| true | true | public void testOrderwithclient(){
Client cl = Client.find("firstname", "Diego").first();
assertNotNull(cl);
Order order = new Order( new Date(System.currentTimeMillis()) , cl);
assertNotNull(order);
order.save();
Detail det = new Detail(COLOR.BLACK,SIZE.MEDIUM,2);
Detail det2 = new Detail(COLOR.BLACK,SIZE.SMALL,3);
order.addDetail(det);
order.addDetail(det2);
order.save();
Payment pay = new Payment(new Date(System.currentTimeMillis()), 58.84F);
order.addPayment(pay);
assertTrue(order.payments.size()>0);
order.save();
}
| public void testOrderwithclient(){
Client cl = Client.find("firstname", "Diego").first();
assertNotNull(cl);
Order order = new Order( new Date(System.currentTimeMillis()) , cl);
assertNotNull(order);
order.save();
Detail det = new Detail(1,2,2);
Detail det2 = new Detail(1,2,3);
order.addDetail(det);
order.addDetail(det2);
order.save();
Payment pay = new Payment(new Date(System.currentTimeMillis()), 58.84F);
order.addPayment(pay);
assertTrue(order.payments.size()>0);
order.save();
}
|
diff --git a/app/in/partake/model/daofacade/EventDAOFacade.java b/app/in/partake/model/daofacade/EventDAOFacade.java
index 0b7f0d2..9941a34 100644
--- a/app/in/partake/model/daofacade/EventDAOFacade.java
+++ b/app/in/partake/model/daofacade/EventDAOFacade.java
@@ -1,229 +1,229 @@
package in.partake.model.daofacade;
import in.partake.base.TimeUtil;
import in.partake.base.Util;
import in.partake.model.EventCommentEx;
import in.partake.model.EventEx;
import in.partake.model.IPartakeDAOs;
import in.partake.model.UserEx;
import in.partake.model.dao.DAOException;
import in.partake.model.dao.DataIterator;
import in.partake.model.dao.PartakeConnection;
import in.partake.model.dao.access.IEventActivityAccess;
import in.partake.model.dto.Event;
import in.partake.model.dto.EventActivity;
import in.partake.model.dto.EventComment;
import in.partake.model.dto.EventFeed;
import in.partake.model.dto.EventTicket;
import in.partake.model.dto.MessageEnvelope;
import in.partake.model.dto.TwitterMessage;
import in.partake.model.dto.User;
import in.partake.model.dto.UserTwitterLink;
import in.partake.model.dto.auxiliary.MessageDelivery;
import in.partake.resource.PartakeProperties;
import in.partake.service.EventSearchServiceException;
import in.partake.service.IEventSearchService;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class EventDAOFacade {
private static final Logger logger = Logger.getLogger(EventDAOFacade.class);
public static EventEx getEventEx(PartakeConnection con, IPartakeDAOs daos, String eventId) throws DAOException {
Event event = daos.getEventAccess().find(con, eventId);
if (event == null) { return null; }
UserEx owner = UserDAOFacade.getUserEx(con, daos, event.getOwnerId());
if (owner == null) { return null; }
String feedId = daos.getEventFeedAccess().findByEventId(con, eventId);
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, eventId);
List<User> editors = new ArrayList<User>();
if (event.getEditorIds() != null) {
for (String editorId : event.getEditorIds()) {
User editor = daos.getUserAccess().find(con, editorId);
if (editor != null)
editors.add(editor);
}
}
List<Event> relatedEvents = new ArrayList<Event>();
if (event.getRelatedEventIds() != null) {
for (String relatedEventId : event.getRelatedEventIds()) {
if (!Util.isUUID(relatedEventId))
continue;
Event relatedEvent = daos.getEventAccess().find(con, relatedEventId);
if (relatedEvent != null)
relatedEvents.add(relatedEvent);
}
}
return new EventEx(event, owner, feedId, tickets, editors, relatedEvents);
}
/**
* event をデータベースに保持します。
* @return event id
*/
public static String create(PartakeConnection con, IPartakeDAOs daos, Event eventEmbryo) throws DAOException {
String eventId = daos.getEventAccess().getFreshId(con);
eventEmbryo.setId(eventId);
daos.getEventAccess().put(con, eventEmbryo);
// Feed Dao にも挿入。
String feedId = daos.getEventFeedAccess().findByEventId(con, eventId);
if (feedId == null) {
feedId = daos.getEventFeedAccess().getFreshId(con);
daos.getEventFeedAccess().put(con, new EventFeed(feedId, eventId));
}
// Event Activity にも挿入
{
IEventActivityAccess eaa = daos.getEventActivityAccess();
EventActivity activity = new EventActivity(eaa.getFreshId(con), eventEmbryo.getId(), "イベントが登録されました : " + eventEmbryo.getTitle(), eventEmbryo.getDescription(), eventEmbryo.getCreatedAt());
eaa.put(con, activity);
}
// さらに、twitter bot がつぶやく (private の場合はつぶやかない)
if (eventEmbryo.isSearchable())
tweetNewEventArrival(con, daos, eventEmbryo);
return eventEmbryo.getId();
}
public static String copy(PartakeConnection con, IPartakeDAOs daos, UserEx user, Event event) throws DAOException {
// --- copy event.
Event newEvent = new Event(event);
newEvent.setId(null);
newEvent.setTitle(Util.shorten("コピー -- " + event.getTitle(), 100));
newEvent.setDraft(true);
newEvent.setOwnerId(user.getId());
String newEventId = EventDAOFacade.create(con, daos, newEvent);
newEvent.setId(newEventId);
// --- copy ticket.
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, event.getId());
for (EventTicket ticket : tickets) {
EventTicket newTicket = new EventTicket(ticket);
newTicket.setId(daos.getEventTicketAccess().getFreshId(con));
newTicket.setEventId(newEventId);
daos.getEventTicketAccess().put(con, newTicket);
}
return newEventId;
}
public static void modify(PartakeConnection con, IPartakeDAOs daos, Event eventEmbryo) throws DAOException {
assert eventEmbryo != null;
assert eventEmbryo.getId() != null;
// master を update
daos.getEventAccess().put(con, eventEmbryo);
// Event Activity にも挿入
{
IEventActivityAccess eaa = daos.getEventActivityAccess();
EventActivity activity = new EventActivity(eaa.getFreshId(con), eventEmbryo.getId(), "イベントが更新されました : " + eventEmbryo.getTitle(), eventEmbryo.getDescription(), eventEmbryo.getCreatedAt());
eaa.put(con, activity);
}
// TODO: twitter bot が更新をつぶやいてもいいような気がする。
}
public static void recreateEventIndex(PartakeConnection con, IPartakeDAOs daos, IEventSearchService searchService) throws DAOException, EventSearchServiceException {
searchService.truncate();
DataIterator<Event> it = daos.getEventAccess().getIterator(con);
try {
while (it.hasNext()) {
Event event = it.next();
if (event == null) { continue; }
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, event.getId());
if (!event.isSearchable())
searchService.remove(event.getId());
else if (searchService.hasIndexed(event.getId()))
searchService.update(event, tickets);
else
searchService.create(event, tickets);
}
} finally {
it.close();
}
}
// ----------------------------------------------------------------------
// Comments
public static EventCommentEx getCommentEx(PartakeConnection con, IPartakeDAOs daos, String commentId) throws DAOException {
EventComment comment = daos.getCommentAccess().find(con, commentId);
if (comment == null) { return null; }
UserEx user = UserDAOFacade.getUserEx(con, daos, comment.getUserId());
if (user == null) { return null; }
return new EventCommentEx(comment, user);
}
public static List<EventCommentEx> getCommentsExByEvent(PartakeConnection con, IPartakeDAOs daos, String eventId) throws DAOException {
List<EventCommentEx> result = new ArrayList<EventCommentEx>();
con.beginTransaction();
DataIterator<EventComment> iterator = daos.getCommentAccess().getCommentsByEvent(con, eventId);
try {
if (iterator == null) { return result; }
while (iterator.hasNext()) {
EventComment comment = iterator.next();
if (comment == null) { continue; }
String commentId = comment.getId();
if (commentId == null) { continue; }
EventCommentEx commentEx = getCommentEx(con, daos, commentId);
if (commentEx == null) { continue; }
result.add(commentEx);
}
} finally {
iterator.close();
}
return result;
}
public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
- String eventURL = event.getUrl(); // always 20
+ String eventURL = event.getEventURL(); // Always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
- TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, twitterMessageId, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
+ TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, message, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
}
| false | true | public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
String eventURL = event.getUrl(); // always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, twitterMessageId, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
| public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
String eventURL = event.getEventURL(); // Always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, message, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
|
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java b/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
index c9ce14b2f..c6961f1a7 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
@@ -1,118 +1,120 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.servlet.filter.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.fedoraproject.candlepin.config.Config;
import org.fedoraproject.candlepin.resource.ForbiddenException;
import org.fedoraproject.candlepin.service.UserServiceAdapter;
import com.google.inject.Inject;
/**
* BasicAuthViaUserServiceFilter
*/
public class BasicAuthViaUserServiceFilter implements Filter {
private Logger log = Logger.getLogger(BasicAuthViaDbFilter.class);
private Config config = null;
private UserServiceAdapter userServiceAdapter;
@Inject
public BasicAuthViaUserServiceFilter(Config config, UserServiceAdapter userServiceAdapter) {
this.config = config;
this.userServiceAdapter = userServiceAdapter;
}
public BasicAuthViaUserServiceFilter() {
config = new Config();
}
public void init(FilterConfig filterConfig) throws ServletException {
//this.filterConfig = filterConfig;
}
public void destroy() {
//this.filterConfig = null;
}
// config has to be overridable for testing
public void setConfig(Config configuration) {
this.config = configuration;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
log.debug("in basic auth filter");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (httpRequest.getMethod().equals("POST")) {
processPost(request, response, chain, httpRequest, httpResponse);
}
else {
// Anything that is not a POST is passed through
chain.doFilter(request, response);
}
log.debug("leaving basic auth filter");
}
private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
- if(doAuth(userpass[0], userpass[1])){
+ if (doAuth(userpass[0], userpass[1])) {
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
- }else{
+ }
+ else {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
- }catch (Exception ex) {
+ }
+ catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
private boolean doAuth(String username, String password) throws ForbiddenException {
return userServiceAdapter.validateUser(username, password);
}
}
| false | true | private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
if(doAuth(userpass[0], userpass[1])){
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
}else{
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
| private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
if (doAuth(userpass[0], userpass[1])) {
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
}
else {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
index 6df75eb75..6abcc2b0f 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
@@ -1,401 +1,401 @@
/*
* ====================================================================
* Copyright (c) 2004-2011 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.wc17;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler;
import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNEventFactory;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumInputStream;
import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumOutputStream;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.PristineContentsInfo;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.WritableBaseInfo;
import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.WCDbInfo.InfoField;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc2.SvnChecksum;
import org.tmatesoft.svn.core.wc2.SvnCommitItem;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.4
* @author TMate Software Ltd.
*/
public class SVNCommitter17 implements ISVNCommitPathHandler {
private SVNWCContext myContext;
private Map<String, SvnCommitItem> myCommittables;
private SVNURL myRepositoryRoot;
private Map<File, SvnChecksum> myMd5Checksums;
private Map<File, SvnChecksum> mySha1Checksums;
private Map<String, SvnCommitItem> myModifiedFiles;
private SVNDeltaGenerator myDeltaGenerator;
private SVNCommitter17(SVNWCContext context, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, Collection<File> tmpFiles, Map<File, SvnChecksum> md5Checksums,
Map<File, SvnChecksum> sha1Checksums) {
myContext = context;
myCommittables = committables;
myRepositoryRoot = repositoryRoot;
myMd5Checksums = md5Checksums;
mySha1Checksums = sha1Checksums;
myModifiedFiles = new TreeMap<String, SvnCommitItem>();
}
public static SVNCommitInfo commit(SVNWCContext context, Collection<File> tmpFiles, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, ISVNEditor commitEditor,
Map<File, SvnChecksum> md5Checksums, Map<File, SvnChecksum> sha1Checksums) throws SVNException {
SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRoot, tmpFiles, md5Checksums, sha1Checksums);
SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1);
committer.sendTextDeltas(commitEditor);
return commitEditor.closeEdit();
}
public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
- SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT_TEXT_BASE, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
| true | true | public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT_TEXT_BASE, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
| public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
|
diff --git a/src/com/group7/project/MainActivity.java b/src/com/group7/project/MainActivity.java
index 24da757..2955e53 100644
--- a/src/com/group7/project/MainActivity.java
+++ b/src/com/group7/project/MainActivity.java
@@ -1,484 +1,484 @@
package com.group7.project;
import java.lang.reflect.Field;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.group7.project.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.GpsStatus;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends MapActivity implements BuildingCoordinates
{
private MapView mapView; // The map view used for higher level functions
private MapController mapController; // But most processing will happen with the map controller
private LocationManager locationManager; // Location manager deals with things to do with current device location (GPS)
private LocationListener locationListener; // The listener that checks for all events to do with location (GPS turned on/off, location change, etc.
private boolean trackingUser = false; // Boolean value keeps track of whether or not we are currently locked onto and tracking the user's location
static int markerLoc = -1; // Used to keep track of the user's location marker in the mapView list of overlays
ToggleButton toggleTrackingButton; // The button used to toggle turning user lock-on tracking on and off
GeoPoint userPoint; // The user's coordinates
// List<Building> listOfBuildings; // Listing of all buildings in BuildingCoordinates.java
private float distanceToBuilding; // Calculates distance between user and center point of building
private String currentBuilding = "(none)"; // String value to keep track of the building we are currently in
private Activity activity = this;
// private GoogleMap mMap;
/****************
* toggleUserTracking
*
* @param v - The view that called this function
*
* Called on click of toggleTrackingButton.
* Will turn lock-on tracking on and off, and update variables and buttons accordingly
*
*/
public void toggleUserTracking(View v)
{
//checks if a user point is set yet, or if the GPS is not turned on
if (userPoint == null || !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(getBaseContext(), "Location not set by GPS", Toast.LENGTH_SHORT).show();
toggleTrackingButton.setChecked(false);
trackingUser = false; //redundant code for just in case situations
}
else
{
trackingUser = !trackingUser; //toggle the lock-on
toggleTrackingButton.setChecked(trackingUser); //turn button on/off
if (trackingUser)
{
mapController.animateTo(userPoint); //instantly focus on user's current location
}
}
}
/****************
* dispatchTouchEvent
*
* @param event - The event that called this function
*
* dispatchTouchEvent can handle many, MANY things. Right now all we need it for is to check
* when the user has panned the screen (MotionEvent.ACTION_MOVE).
* If the user has moved the screen around, then we should turn off the lock-on tracking of their location
* But they will have needed to have moved more than 70... units?
* This was to fix issues with pressing the toggle button and it also registering as movement, meaning the toggle
* would want to turn tracking off, but this function would do it first, so then the toggle would just turn it back
* on again
*
* Could use this function later to check on keeping the user within our required boundaries with use of LatLngBounds
*
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
float startX = event.getX();
float startY = event.getY();
float distanceSum = 0;
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++)
{
// historical point
float hx = event.getHistoricalX(0, h);
float hy = event.getHistoricalY(0, h);
// distance between startX,startY and historical point
float dx = (hx-startX);
float dy = (hy-startY);
distanceSum += Math.sqrt(dx*dx+dy*dy);
// make historical point the start point for next loop iteration
startX = hx;
startY = hy;
}
// add distance from last historical point to event's point
float dx = (event.getX(0)-startX);
float dy = (event.getY(0)-startY);
distanceSum += Math.sqrt(dx*dx+dy*dy);
if (distanceSum > 70.0)
{
trackingUser = false;
toggleTrackingButton.setChecked(false);
}
}
return super.dispatchTouchEvent(event);
}
/*
//LIMIT TO CAMPUS - THIS IS HARD
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
GeoPoint newPoint;
final float minLong = -97.156992f;
final float maxLong = -97.123303f;
final float minLat = 49.805292f;
final float maxLat = 49.813758f;
int currLat;
int currLong;
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
newPoint = mapView.getProjection().fromPixels((int)event.getX(), (int)event.getY());
currLat = newPoint.getLatitudeE6();
currLong = newPoint.getLongitudeE6();
float temp = currLat - minLat;
int minLatInt = (int)(minLat * 1E6);
if ((currLat - minLatInt) < 0)
{
newPoint = new GeoPoint(minLatInt, currLong);
//mapController.stopPanning();
//mapController.setCenter(newPoint);
mapView.invalidate();
}
}
return super.dispatchTouchEvent(event);
}
*/
/****************
* onCreate
*
* @param savedInstanceState - Holds any dynamic data held in onSaveInstanceState (we don't need to worry about this)
*
* The initial set up of everything that needs to be done when the view is first created
* ie. when the app is first run
*
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
//Get a listing of all the buildings and save them so we can
// access them easier later
AllBuildings[0] = E1;
AllBuildings[1] = E2;
AllBuildings[2] = E3;
AllBuildings[3] = UCENTRE;
AllBuildings[4] = HOUSE;
//starting latitude and longitude. currently a location near EITC
final float startLat = 49.808503f;
final float startLong = -97.135824f;
super.onCreate(savedInstanceState); //run the parent's onCreate, where I imagine the UI stuff gets taken care of
setContentView(R.layout.activity_main); //set our main activity to be the default view
GeoPoint centerPoint = new GeoPoint((int)(startLat * 1E6), (int)(startLong * 1E6)); //create a GeoPoint based on those values
mapView = (MapView) findViewById(R.id.mapView); //get the MapView object from activity_main
toggleTrackingButton = (ToggleButton) findViewById(R.id.toggleTrackingButton); //get the toggleTrackingButton from activity_main
//settings on what to show on the map
//mapView.setSatellite(true);
//mapView.setTraffic(true);
//GPS setup stuff
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.addGpsStatusListener((Listener) locationListener);
//This next line here sets our listener to check for changes to the GPS
//The first integer value is the minimum time to wait before taking another update (in milliseconds)
//So entering 500 here means it will only listen and run it's functions every 0.5 seconds
//The second integer value is the minimum change in distance required before the functions will be called (in metres)
//So entering 4 here means that unless the user has moved 4 metres from the last time we did an update, nothing will be called
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//mapView.setBuiltInZoomControls(true); //turn on zoom controls
mapController = mapView.getController();
mapController.setZoom(20); //set default zoom level
mapController.setCenter(centerPoint); //move center of map
// Overlays stuff could be very important later on. I don't quite fully understand it yet myself
// All these do right now is display little Android icons at the North-East and South-West corners
// of a building (which I currently have set to E1).
// ***** THIS IS ONLY DEBUG CODE USED TO CHECK THE BOUNDS OF BUILDINGS ENTERED *******
// See the BuildingCoordinates.java file for more details on buildings
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
for(Building b:AllBuildings)
{
GeoPoint point = new GeoPoint(
(int) (b.getCenter().latitude * 1E6),
(int) (b.getCenter().longitude * 1E6)
);
OverlayItem overlayitem = new OverlayItem(point, b.getName(), "Founded: 1900");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
}
/****************
* onCreateOptionsMenu
*
* @param menu - The menu we're gonna create? Not too sure about this function
*
* I imagine this could come in handy later if we want to do some menu stuff.
* Would need to read up on it more
*
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/****************
* onBackPressed
*
* Called when the user presses the back button on the device
*
*/
public void onBackPressed()
{
//pressing the back button on the device will kill the app
System.exit(0);
}
/****************
* isRouteDisplayed
*
* Used if we want to display routing information
*/
@Override
protected boolean isRouteDisplayed()
{
//I should figure out what this is about
return true;
}
private class GPSLocationListener implements LocationListener, GpsStatus.Listener
{
private int GPSEvent = GpsStatus.GPS_EVENT_STOPPED; // Keeps track of the current status of the GPS
/****************
* onLocationChanged
*
* @param location - User's changed location
*
* Called any time the user's location changes
* So far, we're using it to update the location of the user's icon, but can later be used to check
* if a user is within the range of a building
*
*/
@Override
public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
- "ENTERED " + HOUSE.getName(),
+ "ENTERED " + b.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
- if(minDistance == 70)//tell user they are near a building only once when they get about 70 metres close to it
+ if(minDistance == 70 && minBuilding != null)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
/****************
* onProviderDisabled
*
* @param provider - Name of the location provider that has been disabled
*
* We only use this right now to keep all our tracking information consistent when the user
* decides to turn off the GPS
*/
@Override
public void onProviderDisabled(String provider)
{
if (provider.equals(LocationManager.GPS_PROVIDER))
{
trackingUser = false;
toggleTrackingButton.setChecked(false);
}
}
@Override
public void onProviderEnabled(String provider)
{
//Toast.makeText(getBaseContext(), "Provider enabled (" + provider + ")", Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
//Toast.makeText(getBaseContext(), "Status changed: (" + provider + " - " + status + ")", Toast.LENGTH_LONG).show();
}
/****************
* onGpsStatusChanged
*
* @param event - The integer value of the event that has occurred
*
* Used to update the GPSEvent variable so that we know what's going on with the GPS
*
* Called when the GPS' status has changed
* 1 = GPS_EVENT_STARTED (GPS turned on)
* 2 = GPS_EVENT_STOPPED (GPS turned off)
* 3 = GPS_EVENT_FIRST_FIX (Got fix on GPS satellite after having nothing and searching)
* 4 = GPS_EVENT_SATELLITE_STATUS (Event sent periodically to report GPS satellite status, we don't care about this)
*/
@Override
public void onGpsStatusChanged(int event)
{
//System.out.println("GPS Status: " + event);
if (event != GpsStatus.GPS_EVENT_SATELLITE_STATUS)
{
GPSEvent = event;
}
}
}
private class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point)
{
pointToDraw = point;
}
/*
public GeoPoint getPointToDraw()
{
return pointToDraw;
}
*/
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
| false | true | public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
"ENTERED " + HOUSE.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
if(minDistance == 70)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
| public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
"ENTERED " + b.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
if(minDistance == 70 && minBuilding != null)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
|
diff --git a/src/de/typology/trainers/LuceneNGramIndexer.java b/src/de/typology/trainers/LuceneNGramIndexer.java
index 4007d875..5e3f1463 100644
--- a/src/de/typology/trainers/LuceneNGramIndexer.java
+++ b/src/de/typology/trainers/LuceneNGramIndexer.java
@@ -1,133 +1,132 @@
package de.typology.trainers;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import de.typology.utils.Config;
import de.typology.utils.IOHelper;
/**
*
* @author rpickhardt
*
*/
public class LuceneNGramIndexer {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
}
public static void run(String normalizedNGrams, String indexNGrams)
throws NumberFormatException, IOException {
long startTime = System.currentTimeMillis();
for (int nGramType = 2; nGramType < 6; nGramType++) {
LuceneNGramIndexer indexer = new LuceneNGramIndexer(indexNGrams
+ nGramType);
indexer.index(normalizedNGrams + nGramType + "/");
indexer.close();
}
long endTime = System.currentTimeMillis();
IOHelper.strongLog((endTime - startTime) / 1000
+ " seconds for indexing " + Config.get().normalizedNGrams);
}
private BufferedReader reader;
private IndexWriter writer;
private String line;
private String[] lineSplit;
private Float edgeCount;
public LuceneNGramIndexer(String nGramDir) throws IOException {
Directory dir = FSDirectory.open(new File(nGramDir));
// TODO: change Analyzer since this one makes stuff case insensitive...
// also change this in quering: see important note:
// http://oak.cs.ucla.edu/cs144/projects/lucene/index.html in chapter
// 2.0
// http://stackoverflow.com/questions/2487736/lucene-case-sensitive-insensitive-search
// Analyzer analyzer = new TypologyAnalyzer(Version.LUCENE_40);
Analyzer analyzer = new KeywordAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
config.setOpenMode(OpenMode.CREATE);
this.writer = new IndexWriter(dir, config);
}
public void close() throws IOException {
this.writer.close();
}
/**
* Given a directory containing typology edge files, index() builds a Lucene
* index. See getDocument() for document structure.
*
* @param dataDir
* @param filter
* @return
* @throws NumberFormatException
* @throws IOException
*/
public int index(String dataDir) throws NumberFormatException, IOException {
ArrayList<File> files = IOHelper.getDirectory(new File(dataDir));
for (File file : files) {
if (file.getName().contains("distribution")) {
IOHelper.log("skipping " + file.getAbsolutePath());
continue;
}
IOHelper.log("indexing " + file.getAbsolutePath());
this.indexFile(file);
}
return files.size();
}
private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
- .parseFloat(this.lineSplit[this.lineSplit.length - 1]
- .substring(1));
+ .parseFloat(this.lineSplit[this.lineSplit.length - 1]);
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
private Document getDocument(String source, String target, Float count) {
Document document = new Document();
document.add(new StringField("src", source, Field.Store.NO));
document.add(new StringField("tgt", target, Field.Store.YES));
document.add(new FloatField("cnt", count, Field.Store.YES));
return document;
}
}
| true | true | private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
.parseFloat(this.lineSplit[this.lineSplit.length - 1]
.substring(1));
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
| private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
.parseFloat(this.lineSplit[this.lineSplit.length - 1]);
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index 39c81e4..b4ad10b 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,687 +1,687 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.server.Server;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.map.fastfindgrid.Traceable;
import java.util.List;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Polygon;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private Traceable caster3;
private SimplePosition target;
/**
* Mittelpunkt für arc-Bewegungen
*/
private SimplePosition around;
/**
* Aktuelle Bewegung eine Kurve?
*/
private boolean arc;
/**
* Richtung der Kurve (true = Plus)
*/
private boolean arcDirection;
/**
* Wie weit (im Bogenmaß) wir auf dem Kreis laufen müssen
*/
private double tethaDist;
/**
* Wie weit wir (im Bogenmaß) auf dem Kreis schon gelaufen sind
*/
private double movedTetha;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
private GroupMember pathManager;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im Weg steht und man wartet bis es den Weg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 3000000000l;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
/**
* Ein simples Flag, das nach dem Kollisionstest gesetzt ist.
*/
private boolean colliding = false;
/**
* Zeigt nach dem Kollisionstest auf das letzte (kollidierende) Objekt.
*/
private Moveable lastObstacle;
/**
* Wegen wem wir zuletzt warten mussten.
*/
private Moveable waitFor;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, Traceable caster3, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.caster3 = caster3;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
movedTetha += Math.abs(newTetha - tetha);
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
newTetha = -2 * Math.PI + newTetha;
} else if (newTetha < -Math.PI) {
newTetha = 2 * Math.PI + newTetha;
}
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
waitFor = lastObstacle;
if (caster2.getMidLevelManager().stayWaiting(caster2, waitFor)) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Es wurde eine Umleitung eingestellt
wait = false;
trigger();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle);
if (wait) {
waitStartTime = System.nanoTime();
waitFor = lastObstacle;
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
boolean arcDone = false;
if (arc) {
arcDone = movedTetha >= tethaDist;
}
if (((!arc && vec.isOpposite(nextVec)) || arcDone || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
private void setMoveable(FloatingPointPosition from, FloatingPointPosition to) {
caster2.setMainPosition(to);
// Neuer Sektor?
while (pathManager.nextSectorBorder() != null && pathManager.nextSectorBorder().sidesDiffer(from, to)) {
// Ja, alten löschen und neuen setzen!
SectorChangingEdge edge = pathManager.borderCrossed();
caster2.setMyPoly(edge.getNext(caster2.getMyPoly()));
}
// Schnellsuchraster aktualisieren:
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* Falls arc true ist, werden arcDirection und arcCenter ausgewertet, sonst nicht.
* @param pos die Zielposition
* @param arc ob das Ziel auf einer Kurve angesteuert werden soll (true)
* @param arcDirection Richtung der Kurve (true - Bogenmaß-Plusrichtung)
* @param arcCenter um welchen Punkt gedreht werden soll.
*/
public synchronized void setTargetVector(SimplePosition pos, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null (" + arc + ")");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position (" + arc + ")");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
this.arc = arc;
this.arcDirection = arcDirection;
this.around = arcCenter;
this.movedTetha = 0;
if (arc) {
// Länge des Kreissegments berechnen
double startTetha = Math.atan2(caster2.getPrecisePosition().y() - around.y(), caster2.getPrecisePosition().x() - around.x());
double targetTetha = Math.atan2(target.y() - around.y(), target.x() - around.x());
if (arcDirection) {
tethaDist = targetTetha - startTetha;
} else {
tethaDist = startTetha - targetTetha;
}
if (tethaDist < 0) {
tethaDist = 2 * Math.PI + tethaDist;
}
}
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
changeSpeed(speed);
setTargetVector(pos, arc, arcDirection, arcCenter);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Untersucht die gegebene Route auf Echtzeitkollision.
* Sollte alles frei sein, wird to zurückgegeben.
* Ansonsten gibts eine neue Position, bis zu der problemlos gelaufen werden kann.
* Im schlimmsten Fall ist dies die from-Position, die frei sein MUSS!
* @param from von wo wir uns losbewegen
* @param to wohin wir laufen
* @return FloatingPointPosition bis wohin man laufen kann.
*/
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
- SimplePosition s2 = intersections[0];
+ SimplePosition s2 = intersections[1];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
/**
* Hiermit lässt sich herausfinden, ob dieser mover gerade wartet, weil jemand im Weg steht.
* @return
*/
boolean isWaiting() {
return wait;
}
/**
* Hiermit lässt siche herausfinden, wer momentan primär einem Weiterlaufen
* im Weg steht.
* @return Das derzeitige, primäre Hinderniss
*/
Moveable getWaitFor() {
return waitFor;
}
/**
* @return the pathManager
*/
GroupMember getPathManager() {
return pathManager;
}
/**
* @param pathManager the pathManager to set
*/
void setPathManager(GroupMember pathManager) {
this.pathManager = pathManager;
}
/**
* Findet heraus, ob das gegebenen Moveable auf dem gegebenen zu laufenden Abschnitt liegt,
* also eine Kollision darstellt.
* @param t
* @return true, wenn Kollision
*/
private boolean collidesOnArc(Moveable t, SimplePosition around, double colRadius, SimplePosition from, SimplePosition to) {
if (!arc) {
return false;
}
// Muss in +arc-Richtung erfolgen, notfalls start und Ziel tauschen
if (!arcDirection) {
SimplePosition back = from;
from = to;
to = back;
}
// Zuerst auf Nähe des gesamten Kreissegments testen
double dist = t.getPrecisePosition().getDistance(around.toFPP());
double moveRad = from.toFPP().getDistance(around.toFPP());
double minCol = moveRad - colRadius - t.getRadius();
double maxCol = moveRad + colRadius + t.getRadius();
if (dist >= minCol && dist <= maxCol) {
// Mögliche Kollision!
// Winkeltest
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double toTetha = Math.atan2(to.y() - around.y(), to.x() - around.x());
if (toTetha < 0) {
toTetha += 2 * Math.PI;
}
double colTetha = Math.atan2(t.getPrecisePosition().y() - around.y(), t.getPrecisePosition().x() - around.x());
if (colTetha < 0) {
colTetha += 2 * Math.PI;
}
// Zusätzlichen Umlauf beachten
if (toTetha < fromTetha) {
if (colTetha < toTetha) {
colTetha += 2 * Math.PI;
}
toTetha += 2 * Math.PI;
}
if (colTetha >= fromTetha && colTetha <= toTetha) {
// Dann auf jeden Fall
return true;
}
// Sonst weitertesten: Der 6-Punkte-Test
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), (float) t.getRadius());
Vector fromOrtho = new Vector(from.x() - around.x(), from.y() - around.y());
fromOrtho = fromOrtho.normalize().multiply(colRadius);
Vector toOrtho = new Vector(to.x() - around.x(), to.y() - around.y());
toOrtho = toOrtho.normalize().multiply(colRadius);
SimplePosition t1 = from.toVector().add(fromOrtho);
SimplePosition t2 = from.toVector();
SimplePosition t3 = from.toVector().add(fromOrtho.getInverted());
SimplePosition t4 = to.toVector().add(toOrtho);
SimplePosition t5 = to.toVector();
SimplePosition t6 = to.toVector().add(toOrtho.normalize());
if (c.contains((float) t1.x(), (float) t1.y())
|| c.contains((float) t2.x(), (float) t2.y())
|| c.contains((float) t3.x(), (float) t3.y())
|| c.contains((float) t4.x(), (float) t4.y())
|| c.contains((float) t5.x(), (float) t5.y())
|| c.contains((float) t6.x(), (float) t6.y())) {
return true;
}
}
return false;
}
}
| true | true | private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
SimplePosition s2 = intersections[0];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
| private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
SimplePosition s2 = intersections[1];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
|
diff --git a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
index 952a6f2f..f6d6013e 100644
--- a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
+++ b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
@@ -1,1594 +1,1592 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* 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.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.filter.initialization;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.zip.ZipInputStream;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import liquibase.changelog.ChangeSet;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.ImplementationId;
import org.openmrs.api.PasswordException;
import org.openmrs.api.context.Context;
import org.openmrs.module.MandatoryModuleException;
import org.openmrs.module.OpenmrsCoreModuleException;
import org.openmrs.module.web.WebModuleUtil;
import org.openmrs.scheduler.SchedulerUtil;
import org.openmrs.util.DatabaseUpdateException;
import org.openmrs.util.DatabaseUpdater;
import org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback;
import org.openmrs.util.DatabaseUtil;
import org.openmrs.util.InputRequiredException;
import org.openmrs.util.MemoryAppender;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.util.Security;
import org.openmrs.web.Listener;
import org.openmrs.web.WebConstants;
import org.openmrs.web.filter.StartupFilter;
import org.openmrs.web.filter.util.CustomResourseLoader;
import org.openmrs.web.filter.util.ErrorMessageConstants;
import org.openmrs.web.filter.util.FilterUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
/**
* This is the first filter that is processed. It is only active when starting OpenMRS for the very
* first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the
* {@link Listener} wasn't able to find any runtime properties
*/
public class InitializationFilter extends StartupFilter {
private static final Log log = LogFactory.getLog(InitializationFilter.class);
private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml";
private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml";
private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
/**
* The very first page of wizard, that asks user for select his preferred language
*/
private final String CHOOSE_LANG = "chooselang.vm";
/**
* The second page of the wizard that asks for simple or advanced installation.
*/
private final String INSTALL_METHOD = "installmethod.vm";
/**
* The simple installation setup page.
*/
private final String SIMPLE_SETUP = "simplesetup.vm";
/**
* The first page of the advanced installation of the wizard that asks for a current or past
* database
*/
private final String DATABASE_SETUP = "databasesetup.vm";
/**
* The page from where the user specifies the url to a production system
*/
private final String TESTING_PRODUCTION_URL_SETUP = "productionurl.vm";
/**
* The velocity macro page to redirect to if an error occurs or on initial startup
*/
private final String DEFAULT_PAGE = CHOOSE_LANG;
/**
* This page asks whether database tables/demo data should be inserted and what the
* username/password that will be put into the runtime properties is
*/
private final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
/**
* This page lets the user define the admin user
*/
private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
/**
* This page lets the user pick an implementation id
*/
private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
/**
* This page asks for settings that will be put into the runtime properties files
*/
private final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
/**
* A page that tells the user that everything is collected and will now be processed
*/
private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
/**
* A page that lists off what is happening while it is going on. This page has ajax that callst
* he {@value #PROGRESS_VM_AJAXREQUEST} page
*/
private static final String PROGRESS_VM = "progress.vm";
/**
* This url is called by javascript to get the status of the install
*/
private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
public static final String RELEASE_TESTING_MODULE_PATH = "/module/testing/";
/**
* The model object that holds all the properties that the rendered templates use. All
* attributes on this object are made available to all templates via reflection in the
* {@link #renderTemplate(String, Map, httpResponse)} method.
*/
private InitializationWizardModel wizardModel = null;
private InitializationCompletion initJob;
/**
* Variable set to true as soon as the installation begins and set to false when the process
* ends This thread should only be accesses through the synchronized method.
*/
private static boolean isInstallationStarted = false;
// the actual driver loaded by the DatabaseUpdater class
private String loadedDriverString;
/**
* Variable set at the end of the wizard when spring is being restarted
*/
private static boolean initializationComplete = false;
/**
* The login page when the testing install option is selected
*/
public static final String TESTING_AUTHENTICATION_SETUP = "authentication.vm";
synchronized protected void setInitializationComplete(boolean initializationComplete) {
InitializationFilter.initializationComplete = initializationComplete;
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
if (page == null) {
checkLocaleAttributesForFirstTime(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
// get props and render the second page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.currentDatabaseUsername);
wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
wizardModel.currentDatabasePassword);
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
// do step one of the wizard
httpResponse.setContentType("text/html");
// if any body has already started installation
if (isInstallationStarted()) {
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
} else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
httpResponse.setContentType("text/json");
httpResponse.setHeader("Cache-Control", "no-cache");
Map<String, Object> result = new HashMap<String, Object>();
if (initJob != null) {
result.put("hasErrors", initJob.hasErrors());
if (initJob.hasErrors()) {
result.put("errorPage", initJob.getErrorPage());
errors.putAll(initJob.getErrors());
}
result.put("initializationComplete", isInitializationComplete());
result.put("message", initJob.getMessage());
result.put("actionCounter", initJob.getStepsComplete());
if (!isInitializationComplete()) {
result.put("executingTask", initJob.getExecutingTask());
result.put("executedTasks", initJob.getExecutedTasks());
result.put("completedPercentage", initJob.getCompletedPercentage());
}
Appender appender = Logger.getRootLogger().getAppender("MEMORY_APPENDER");
if (appender instanceof MemoryAppender) {
MemoryAppender memoryAppender = (MemoryAppender) appender;
List<String> logLines = memoryAppender.getLogLines();
// truncate the list to the last 5 so we don't overwhelm jquery
if (logLines.size() > 5)
logLines = logLines.subList(logLines.size() - 5, logLines.size());
result.put("logLines", logLines);
} else {
result.put("logLines", new ArrayList<String>());
}
}
httpResponse.getWriter().write(toJSONString(result, true));
}
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
- wizardModel.createTables = true;
+ wizardModel.createTables = false;
wizardModel.addDemoData = false;
- wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
- wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
/**
* This method should be called after the user has left wizard's first page (i.e. choose
* language). It checks if user has changed any of locale related parameters and makes
* appropriate corrections with filter's model or/and with locale attribute inside user's
* session.
*
* @param httpRequest the http request object
*/
private void checkLocaleAttributes(HttpServletRequest httpRequest) {
String localeParameter = httpRequest.getParameter(FilterUtil.LOCALE_ATTRIBUTE);
Boolean rememberLocale = false;
// we need to check if user wants that system will remember his selection of language
if (httpRequest.getParameter(FilterUtil.REMEMBER_ATTRIBUTE) != null)
rememberLocale = true;
if (localeParameter != null) {
String storedLocale = null;
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
storedLocale = httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE).toString();
}
// if user has changed locale parameter to new one
// or chooses it parameter at first page loading
if ((storedLocale == null) || (storedLocale != null && !storedLocale.equals(localeParameter))) {
log.info("Stored locale parameter to session " + localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
}
if (rememberLocale) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, true);
} else {
// we need to reset it if it was set before
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, null);
}
}
}
/**
* It sets locale parameter for current session when user is making first GET http request to
* application. It retrieves user locale from request object and checks if this locale is
* supported by application. If not, it uses {@link Locale#ENGLISH} by default
*
* @param httpRequest the http request object
*/
public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
Locale locale = httpRequest.getLocale();
if (CustomResourseLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
} else {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
}
}
/**
* Verify the database connection works.
*
* @param connectionUsername
* @param connectionPassword
* @param databaseConnectionFinalUrl
* @return true/false whether it was verified or not
*/
private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) {
try {
// verify connection
//Set Database Driver using driver String
Class.forName(loadedDriverString).newInstance();
DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
return true;
}
catch (Exception e) {
errors.put("User account " + connectionUsername + " does not work. " + e.getMessage()
+ " See the error log for more details", null); // TODO internationalize this
log.warn("Error while checking the connection user account", e);
return false;
}
}
/**
* Convenience method to load the runtime properties file.
*
* @return the runtime properties file.
*/
private File getRuntimePropertiesFile() {
File file = null;
String pathName = OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME);
if (pathName != null) {
file = new File(pathName);
} else
file = new File(OpenmrsUtil.getApplicationDataDirectory(), WebConstants.WEBAPP_NAME + "-runtime.properties");
log.debug("Using file: " + file.getAbsolutePath());
return file;
}
/**
* @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
*/
@Override
protected String getTemplatePrefix() {
return "org/openmrs/web/filter/initialization/";
}
/**
* @see org.openmrs.web.filter.StartupFilter#getModel()
*/
@Override
protected Object getModel() {
return wizardModel;
}
/**
* @see org.openmrs.web.filter.StartupFilter#skipFilter()
*/
@Override
public boolean skipFilter(HttpServletRequest httpRequest) {
// If progress.vm makes an ajax request even immediately after initialization has completed
// let the request pass in order to let progress.vm load the start page of OpenMRS
// (otherwise progress.vm is displayed "forever")
return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page")) && !initializationRequired();
}
/**
* Public method that returns true if database+runtime properties initialization is required
*
* @return true if this initialization wizard needs to run
*/
public static boolean initializationRequired() {
return !isInitializationComplete();
}
/**
* @param isInstallationStarted the value to set
*/
protected static synchronized void setInstallationStarted(boolean isInstallationStarted) {
InitializationFilter.isInstallationStarted = isInstallationStarted;
}
/**
* @return true if installation has been started
*/
protected static boolean isInstallationStarted() {
return isInstallationStarted;
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
wizardModel = new InitializationWizardModel();
//set whether need to do initialization work
if (isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
//if runtime-properties file doesn't exist, have to do initialization work
setInitializationComplete(false);
} else {
//if database is not empty, then let UpdaterFilter to judge whether need database update
setInitializationComplete(true);
}
}
private void importTestDataSet(InputStream in, String connectionUrl, String connectionUsername, String connectionPassword)
throws IOException {
File tempFile = null;
FileOutputStream fileOut = null;
try {
ZipInputStream zipIn = new ZipInputStream(in);
zipIn.getNextEntry();
tempFile = File.createTempFile("testDataSet", "dump");
fileOut = new FileOutputStream(tempFile);
IOUtils.copy(zipIn, fileOut);
fileOut.close();
zipIn.close();
URI uri = URI.create(connectionUrl.substring(5));
String host = uri.getHost();
int port = uri.getPort();
TestInstallUtil.addTestData(host, port, wizardModel.databaseName, connectionUsername, connectionPassword,
tempFile.getAbsolutePath());
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fileOut);
if (tempFile != null) {
tempFile.delete();
}
}
}
/**
* @param silent if this statement fails do not display stack trace or record an error in the
* wizard object.
* @param user username to connect with
* @param pw password to connect with
* @param sql String containing sql and question marks
* @param args the strings to fill into the question marks in the given sql
* @return result of executeUpdate or -1 for error
*/
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
Connection connection = null;
try {
String replacedSql = sql;
// TODO how to get the driver for the other dbs...
if (wizardModel.databaseConnection.contains("mysql")) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} else {
replacedSql = replacedSql.replaceAll("`", "\"");
}
String tempDatabaseConnection = "";
if (sql.contains("create database")) {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db
} else {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
}
connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
for (String arg : args) {
arg = arg.replace(";", "^"); // to prevent any sql injection
replacedSql = replacedSql.replaceFirst("\\?", arg);
}
// run the sql statement
Statement statement = connection.createStatement();
return statement.executeUpdate(replacedSql);
}
catch (SQLException sqlex) {
if (!silent) {
// log and add error
log.warn("error executing sql: " + sql, sqlex);
errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null);
}
}
catch (InstantiationException e) {
log.error("Error generated", e);
}
catch (IllegalAccessException e) {
log.error("Error generated", e);
}
catch (ClassNotFoundException e) {
log.error("Error generated", e);
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
log.warn("Error while closing connection", t);
}
}
return -1;
}
/**
* Convenience variable to know if this wizard has completed successfully and that this wizard
* does not need to be executed again
*
* @return true if this has been run already
*/
synchronized private static boolean isInitializationComplete() {
return initializationComplete;
}
/**
* Check if the given value is null or a zero-length String
*
* @param value the string to check
* @param errors the list of errors to append the errorMessage to if value is empty
* @param errorMessageCode the string with code of error message translation to append if value
* is empty
* @return true if the value is non-empty
*/
private boolean checkForEmptyValue(String value, Map<String, Object[]> errors, String errorMessageCode) {
if (value != null && !value.equals("")) {
return true;
}
errors.put(errorMessageCode, null);
return false;
}
/**
* Separate thread that will run through all tasks to complete the initialization. The database
* is created, user's created, etc here
*/
private class InitializationCompletion {
private Thread thread;
private int steps = 0;
private String message = "";
private Map<String, Object[]> errors = new HashMap<String, Object[]>();
private String errorPage = null;
private boolean erroneous = false;
private int completedPercentage = 0;
private WizardTask executingTask;
private List<WizardTask> executedTasks = new ArrayList<WizardTask>();
synchronized public void reportError(String error, String errorPage, Object... params) {
errors.put(error, params);
this.errorPage = errorPage;
erroneous = true;
}
synchronized public boolean hasErrors() {
return erroneous;
}
synchronized public String getErrorPage() {
return errorPage;
}
synchronized public Map<String, Object[]> getErrors() {
return errors;
}
/**
* Start the completion stage. This fires up the thread to do all the work.
*/
public void start() {
setStepsComplete(0);
setInitializationComplete(false);
thread.start();
}
public void waitForCompletion() {
try {
thread.join();
}
catch (InterruptedException e) {
log.error("Error generated", e);
}
}
synchronized protected void setStepsComplete(int steps) {
this.steps = steps;
}
synchronized protected int getStepsComplete() {
return steps;
}
synchronized public String getMessage() {
return message;
}
synchronized public void setMessage(String message) {
this.message = message;
setStepsComplete(getStepsComplete() + 1);
}
/**
* @return the executingTask
*/
synchronized protected WizardTask getExecutingTask() {
return executingTask;
}
/**
* @return the completedPercentage
*/
protected synchronized int getCompletedPercentage() {
return completedPercentage;
}
/**
* @param completedPercentage the completedPercentage to set
*/
protected synchronized void setCompletedPercentage(int completedPercentage) {
this.completedPercentage = completedPercentage;
}
/**
* Adds a task that has been completed to the list of executed tasks
*
* @param task
*/
synchronized protected void addExecutedTask(WizardTask task) {
this.executedTasks.add(task);
}
/**
* @param executingTask the executingTask to set
*/
synchronized protected void setExecutingTask(WizardTask executingTask) {
this.executingTask = executingTask;
}
/**
* @return the executedTasks
*/
synchronized protected List<WizardTask> getExecutedTasks() {
return this.executedTasks;
}
/**
* This class does all the work of creating the desired database, user, updates, etc
*/
public InitializationCompletion() {
Runnable r = new Runnable() {
/**
* TODO split this up into multiple testable methods
*
* @see java.lang.Runnable#run()
*/
public void run() {
try {
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
setMessage("Create database");
setExecutingTask(WizardTask.CREATE_SCHEMA);
// connect via jdbc and create a database
String sql = "create database if not exists `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername,
wizardModel.createDatabasePassword, sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_NEW, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_SCHEMA);
}
if (wizardModel.createDatabaseUser) {
setMessage("Create database user");
setExecutingTask(WizardTask.CREATE_DB_USER);
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
reportError(ErrorMessageConstants.ERROR_DB_CREATE_DB_USER, DEFAULT_PAGE);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_GRANT_PRIV, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername
+ " all privileges to database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_DB_USER);
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
setMessage("Verify that the database connection works");
// redirect to setup page if we got an error
reportError("Unable to connect to database", DEFAULT_PAGE);
return;
}
// save the properties for startup purposes
Properties runtimeProperties = new Properties();
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
if (StringUtils.hasText(wizardModel.databaseDriver))
runtimeProperties.put("connection.driver_class", wizardModel.databaseDriver);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY,
Base64.encode(Security.generateNewInitVector()));
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
Base64.encode(Security.generateNewSecretKey()));
Properties properties = Context.getRuntimeProperties();
properties.putAll(runtimeProperties);
runtimeProperties = properties;
Context.setRuntimeProperties(runtimeProperties);
/**
* A callback class that prints out info about liquibase changesets
*/
class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
private int i = 1;
private String message;
public PrintingChangeSetExecutorCallback(String message) {
this.message = message;
}
/**
* @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet,
* int)
*/
@Override
public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: "
+ changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: "
+ changeSet.getDescription());
setCompletedPercentage(Math.round(i * 100 / numChangeSetsToRun));
}
}
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
setMessage("Executing " + LIQUIBASE_SCHEMA_DATA);
setExecutingTask(WizardTask.CREATE_TABLES);
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS schema file"));
addExecutedTask(WizardTask.CREATE_TABLES);
//reset for this task
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_CORE_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS core data file"));
wizardModel.workLog.add("Created database tables and added core data");
addExecutedTask(WizardTask.ADD_CORE_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
e.getMessage());
log.warn("Error while trying to create tables and demo data", e);
}
}
if (wizardModel.importTestData) {
try {
setMessage("Importing test data");
setExecutingTask(WizardTask.IMPORT_TEST_DATA);
setCompletedPercentage(0);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(wizardModel.productionUrl
+ RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form").openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setUseCaches(false);
importTestDataSet(urlConnection.getInputStream(), finalDatabaseConnectionString,
connectionUsername, connectionPassword);
setMessage("Importing installed modules...");
if (!TestInstallUtil.addZippedTestModules(new ZipInputStream(TestInstallUtil
.getResourceInputStream(wizardModel.productionUrl + RELEASE_TESTING_MODULE_PATH
+ "getModules.htm")))) {
reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_ADD_MODULES, DEFAULT_PAGE,
new Object[] {});
log.warn("Failed to add modules");
}
wizardModel.workLog.add("Imported test data");
addExecutedTask(WizardTask.IMPORT_TEST_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to import test data", e);
return;
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
setMessage("Adding demo data");
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_DEMO_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms"));
wizardModel.workLog.add("Added demo data");
addExecutedTask(WizardTask.ADD_DEMO_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
e.getMessage());
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
setMessage("Updating the database to the latest version");
setCompletedPercentage(0);
setExecutingTask(WizardTask.UPDATE_TO_LATEST);
DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback(
"Updating database tables to latest version "));
addExecutedTask(WizardTask.UPDATE_TO_LATEST);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_UPDATE_TO_LATEST, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to update to the latest database version", e);
return;
}
setExecutingTask(null);
setMessage("Starting OpenMRS");
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
Context.openSession();
// load core modules so that required modules are known at openmrs startup
Listener.loadBundledModules(filterConfig.getServletContext());
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
reportError(ErrorMessageConstants.ERROR_DB_UPDATE, DEFAULT_PAGE, updateEx.getMessage());
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log.warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now");
reportError(ErrorMessageConstants.ERROR_INPUT_REQ, DEFAULT_PAGE);
return;
}
catch (MandatoryModuleException mandatoryModEx) {
log.warn(
"A mandatory module failed to start. Fix the error or unmark it as mandatory to continue.",
mandatoryModEx);
reportError(ErrorMessageConstants.ERROR_MANDATORY_MOD_REQ, DEFAULT_PAGE,
mandatoryModEx.getMessage());
return;
}
catch (OpenmrsCoreModuleException coreModEx) {
log.warn(
"A core module failed to start. Make sure that all core modules (with the required minimum versions) are installed and starting properly.",
coreModEx);
reportError(ErrorMessageConstants.ERROR_CORE_MOD_REQ, DEFAULT_PAGE, coreModEx.getMessage());
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
reportError(ErrorMessageConstants.ERROR_SET_INPL_ID, DEFAULT_PAGE, t.getMessage());
log.warn("Implementation ID could not be set.", t);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, t.getMessage());
log.warn("Unable to complete the startup.", t);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
OpenmrsUtil.storeProperties(runtimeProperties, fos,
"Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
Context.closeSession();
}
catch (IOException e) {
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
}
finally {
if (!hasErrors()) {
// set this so that the wizard isn't run again on next page load
setInitializationComplete(true);
// we should also try to store selected by user language
// if user wants to system will do it for him
FilterUtil.storeLocale(wizardModel.localeToSave);
}
setInstallationStarted(false);
}
}
};
thread = new Thread(r);
}
}
/**
* Check whether openmrs database is empty. Having just one non-liquibase table in the given
* database qualifies this as a non-empty database.
*
* @param props the runtime properties
* @return true/false whether openmrs database is empty or doesn't exist yet
*/
private static boolean isDatabaseEmpty(Properties props) {
if (props != null) {
String databaseConnectionFinalUrl = props.getProperty("connection.url");
if (databaseConnectionFinalUrl == null)
return true;
String connectionUsername = props.getProperty("connection.username");
if (connectionUsername == null)
return true;
String connectionPassword = props.getProperty("connection.password");
if (connectionPassword == null)
return true;
Connection connection = null;
try {
DatabaseUtil.loadDatabaseDriver(databaseConnectionFinalUrl);
connection = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
DatabaseMetaData dbMetaData = (DatabaseMetaData) connection.getMetaData();
String[] types = { "TABLE" };
//get all tables
ResultSet tbls = dbMetaData.getTables(null, null, null, types);
while (tbls.next()) {
String tableName = tbls.getString("TABLE_NAME");
//if any table exist besides "liquibasechangelog" or "liquibasechangeloglock", return false
if (!("liquibasechangelog".equals(tableName)) && !("liquibasechangeloglock".equals(tableName)))
return false;
}
return true;
}
catch (Exception e) {
//pass
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
//pass
}
}
//if catch an exception while query database, then consider as database is empty.
return true;
} else
return true;
}
/**
* Convenience method that loads the database driver
*
* @param connection the database connection string
* @param databaseDriver the database driver class name to load
* @return the loaded driver string
*/
public static String loadDriver(String connection, String databaseDriver) {
String loadedDriverString = null;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(connection, databaseDriver);
log.info("using database driver :" + loadedDriverString);
}
catch (ClassNotFoundException e) {
log.error("The given database driver class was not found. "
+ "Please ensure that the database driver jar file is on the class path "
+ "(like in the webapp's lib folder)");
}
return loadedDriverString;
}
}
| false | true | protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = true;
wizardModel.addDemoData = false;
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
| protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = false;
wizardModel.addDemoData = false;
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
|
diff --git a/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java b/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
index d28691d2..dc9e80ed 100644
--- a/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
+++ b/jamwiki-core/src/main/java/org/jamwiki/utils/LinkUtil.java
@@ -1,440 +1,447 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.utils;
import java.io.File;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.Topic;
import org.jamwiki.model.WikiFile;
import org.jamwiki.model.WikiImage;
/**
* General utility methods for handling both wiki topic links such as
* "Topic?query=param#Section", as well as HTML links of the form
* http://example.com/.
*/
public class LinkUtil {
private static final WikiLogger logger = WikiLogger.getLogger(LinkUtil.class.getName());
/**
*
*/
private LinkUtil() {
}
/**
* Build a query parameter. If root is empty, this method returns
* "?param=value". If root is not empty this method returns root +
* "&param=value". Note that param and value will be URL encoded,
* and if "query" does not start with a "?" then one will be pre-pended.
*
* @param query The existing query parameter, if one is available. If the
* query parameter does not start with "?" then one will be pre-pended.
* @param param The name of the query parameter being appended. This
* value will be URL encoded.
* @param value The value of the query parameter being appended. This
* value will be URL encoded.
* @return The full query string generated using the input parameters.
*/
public static String appendQueryParam(String query, String param, String value) {
String url = "";
if (!StringUtils.isBlank(query)) {
if (!query.startsWith("?")) {
query = "?" + query;
}
url = query + "&";
} else {
url = "?";
}
if (StringUtils.isBlank(param)) {
return query;
}
url += Utilities.encodeAndEscapeTopicName(param) + "=";
if (!StringUtils.isBlank(value)) {
url += Utilities.encodeAndEscapeTopicName(value);
}
return url;
}
/**
* Utility method for building a URL link to a wiki edit page for a
* specified topic.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topic The name of the topic for which an edit link is being
* created.
* @param query Any existing query parameters to append to the edit link.
* This value may be either <code>null</code> or empty.
* @param section The section defined by the name parameter within the
* HTML page for the topic being edited. If provided then the edit link
* will allow editing of only the specified section.
* @return A url that links to the edit page for the specified topic.
* Note that this method returns only the URL, not a fully-formed HTML
* anchor tag.
* @throws Exception Thrown if any error occurs while builing the link URL.
*/
public static String buildEditLinkUrl(String context, String virtualWiki, String topic, String query, int section) throws Exception {
query = LinkUtil.appendQueryParam(query, "topic", topic);
if (section > 0) {
query += "&section=" + section;
}
WikiLink wikiLink = new WikiLink();
// FIXME - hard coding
wikiLink.setDestination("Special:Edit");
wikiLink.setQuery(query);
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
}
/**
* Utility method for building an anchor tag that links to an image page
* and includes the HTML image tag to display the image.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topicName The name of the image for which a link is being
* created.
* @param frame Set to <code>true</code> if the image should display with
* a frame border.
* @param thumb Set to <code>true</code> if the image should display as a
* thumbnail.
* @param align Indicates how the image should horizontally align on the
* page. Valid values are "left", "right" and "center".
* @param caption An optional text caption to display for the image. If
* no caption is used then this value should be either empty or
* <code>null</code>.
* @param maxDimension A value in pixels indicating the maximum width or
* height value allowed for the image. Images will be resized so that
* neither the width or height exceeds this value.
* @param suppressLink If this value is <code>true</code> then the
* generated HTML will include the image tag without a link to the image
* topic page.
* @param style The CSS class to use with the img HTML tag. This value
* can be <code>null</code> or empty if no custom style is used.
* @param escapeHtml Set to <code>true</code> if the caption should be
* HTML escaped. This value should be <code>true</code> in any case
* where the caption is not guaranteed to be free from potentially
* malicious HTML code.
* @return The full HTML required to display an image enclosed within an
* HTML anchor tag that links to the image topic page.
* @throws Exception Thrown if any error occurs while builing the image
* HTML.
*/
public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
+ String html = "";
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
- return "<a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(caption) + "</a>";
+ html += "<a href=\"" + url + "\">";
+ if (escapeHtml) {
+ html += StringEscapeUtils.escapeHtml(caption);
+ } else {
+ html += caption;
+ }
+ html += "</a>";
+ return html;
}
- String html = "";
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
/**
* Build the HTML anchor link to a topic page for a given WikLink object.
*
* @param context The servlet context for the link that is being created.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @param text The text to display as the link content.
* @param style The CSS class to use with the anchor HTML tag. This value
* can be <code>null</code> or empty if no custom style is used.
* @param target The anchor link target, or <code>null</code> or empty if
* no target is needed.
* @param escapeHtml Set to <code>true</code> if the link caption should
* be HTML escaped. This value should be <code>true</code> in any case
* where the caption is not guaranteed to be free from potentially
* malicious HTML code.
* @return An HTML anchor link that matches the given input parameters.
* @throws Exception Thrown if any error occurs while builing the link
* HTML.
*/
public static String buildInternalLinkHtml(String context, String virtualWiki, WikiLink wikiLink, String text, String style, String target, boolean escapeHtml) throws Exception {
String url = LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
String topic = wikiLink.getDestination();
if (StringUtils.isBlank(text)) {
text = topic;
}
if (!StringUtils.isBlank(topic) && StringUtils.isBlank(style)) {
if (InterWikiHandler.isInterWiki(virtualWiki)) {
style = "interwiki";
} else if (!LinkUtil.isExistingArticle(virtualWiki, topic)) {
style = "edit";
}
}
if (!StringUtils.isBlank(style)) {
style = " class=\"" + style + "\"";
} else {
style = "";
}
if (!StringUtils.isBlank(target)) {
target = " target=\"" + target + "\"";
} else {
target = "";
}
if (StringUtils.isBlank(topic) && !StringUtils.isBlank(wikiLink.getSection())) {
topic = wikiLink.getSection();
}
String html = "<a href=\"" + url + "\"" + style + " title=\"" + StringEscapeUtils.escapeHtml(topic) + "\"" + target + ">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(text);
} else {
html += text;
}
html += "</a>";
return html;
}
/**
* Build a URL to the topic page for a given topic.
*
* @param context The servlet context path. If this value is
* <code>null</code> then the resulting URL will NOT include context path,
* which breaks HTML links but is useful for servlet redirection URLs.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param topic The topic name for the URL that is being generated.
* @throws Exception Thrown if any error occurs while builing the link
* URL.
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, String topic) throws Exception {
if (StringUtils.isBlank(topic)) {
return null;
}
WikiLink wikiLink = LinkUtil.parseWikiLink(topic);
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, wikiLink);
}
/**
* Build a URL to the topic page for a given topic.
*
* @param context The servlet context path. If this value is
* <code>null</code> then the resulting URL will NOT include context path,
* which breaks HTML links but is useful for servlet redirection URLs.
* @param virtualWiki The virtual wiki for the link that is being created.
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @throws Exception Thrown if any error occurs while builing the link
* URL.
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, WikiLink wikiLink) throws Exception {
String topic = wikiLink.getDestination();
String section = wikiLink.getSection();
String query = wikiLink.getQuery();
if (StringUtils.isBlank(topic) && !StringUtils.isBlank(section)) {
return "#" + Utilities.encodeAndEscapeTopicName(section);
}
if (!LinkUtil.isExistingArticle(virtualWiki, topic)) {
return LinkUtil.buildEditLinkUrl(context, virtualWiki, topic, query, -1);
}
String url = "";
if (context != null) {
url += context;
}
// context never ends with a "/" per servlet specification
url += "/";
// get the virtual wiki, which should have been set by the parent servlet
url += Utilities.encodeAndEscapeTopicName(virtualWiki);
url += "/";
url += Utilities.encodeAndEscapeTopicName(topic);
if (!StringUtils.isBlank(query)) {
if (!query.startsWith("?")) {
url += "?";
}
url += query;
}
if (!StringUtils.isBlank(section)) {
if (!section.startsWith("#")) {
url += "#";
}
url += Utilities.encodeAndEscapeTopicName(section);
}
return url;
}
/**
* Generate the HTML for an interwiki anchor link.
*
* @param wikiLink The WikiLink object containing all relevant information
* about the link being generated.
* @return The HTML anchor tag for the interwiki link.
*/
public static String interWiki(WikiLink wikiLink) {
// remove namespace from link destination
String destination = wikiLink.getDestination();
String namespace = wikiLink.getNamespace();
destination = destination.substring(wikiLink.getNamespace().length() + NamespaceHandler.NAMESPACE_SEPARATOR.length());
String url = InterWikiHandler.formatInterWiki(namespace, destination);
String text = (!StringUtils.isBlank(wikiLink.getText())) ? wikiLink.getText() : wikiLink.getDestination();
return "<a class=\"interwiki\" rel=\"nofollow\" title=\"" + text + "\" href=\"" + url + "\">" + text + "</a>";
}
/**
* Utility method for determining if an article name corresponds to a valid
* wiki link. In this case an "article name" could be an existing topic, a
* "Special:" page, a user page, an interwiki link, etc. This method will
* return true if the given name corresponds to a valid special page, user
* page, topic, or other existing article.
*
* @param virtualWiki The virtual wiki for the topic being checked.
* @param articleName The name of the article that is being checked.
* @return <code>true</code> if there is an article that exists for the given
* name and virtual wiki.
* @throws Exception Thrown if any error occurs during lookup.
*/
public static boolean isExistingArticle(String virtualWiki, String articleName) throws Exception {
if (StringUtils.isBlank(virtualWiki) || StringUtils.isBlank(articleName)) {
return false;
}
if (PseudoTopicHandler.isPseudoTopic(articleName)) {
return true;
}
if (InterWikiHandler.isInterWiki(articleName)) {
return true;
}
if (StringUtils.isBlank(Environment.getValue(Environment.PROP_BASE_FILE_DIR)) || !Environment.getBooleanValue(Environment.PROP_BASE_INITIALIZED)) {
// not initialized yet
return false;
}
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, articleName, false, null);
return (topic != null);
}
/**
* Parse a topic name of the form "Topic?Query#Section", and return a WikiLink
* object representing the link.
*
* @param raw The raw topic link text.
* @return A WikiLink object that represents the link.
*/
public static WikiLink parseWikiLink(String raw) {
// note that this functionality was previously handled with a regular
// expression, but the expression caused CPU usage to spike to 100%
// with topics such as "Urnordisch oder Nordwestgermanisch?"
String processed = raw.trim();
WikiLink wikiLink = new WikiLink();
if (StringUtils.isBlank(processed)) {
return new WikiLink();
}
// first look for a section param - "#..."
int sectionPos = processed.indexOf('#');
if (sectionPos != -1 && sectionPos < processed.length()) {
String sectionString = processed.substring(sectionPos + 1);
wikiLink.setSection(sectionString);
if (sectionPos == 0) {
// link is of the form #section, no more to process
return wikiLink;
}
processed = processed.substring(0, sectionPos);
}
// now see if the link ends with a query param - "?..."
int queryPos = processed.indexOf('?', 1);
if (queryPos != -1 && queryPos < processed.length()) {
String queryString = processed.substring(queryPos + 1);
wikiLink.setQuery(queryString);
processed = processed.substring(0, queryPos);
}
// since we're having so much fun, let's find a namespace (default empty).
String namespaceString = "";
int namespacePos = processed.indexOf(':', 1);
if (namespacePos != -1 && namespacePos < processed.length()) {
namespaceString = processed.substring(0, namespacePos);
}
wikiLink.setNamespace(namespaceString);
String topic = processed;
if (namespacePos > 0 && (namespacePos + 1) < processed.length()) {
// get namespace, unless topic ends with a colon
topic = processed.substring(namespacePos + 1);
}
wikiLink.setArticle(Utilities.decodeTopicName(topic, true));
// destination is namespace + topic
wikiLink.setDestination(Utilities.decodeTopicName(processed, true));
return wikiLink;
}
}
| false | true | public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
return "<a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(caption) + "</a>";
}
String html = "";
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
| public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, int maxDimension, boolean suppressLink, String style, boolean escapeHtml) throws Exception {
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
WikiLink uploadLink = LinkUtil.parseWikiLink("Special:Upload");
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, uploadLink, topicName, "edit", null, true);
}
WikiFile wikiFile = WikiBase.getDataHandler().lookupWikiFile(virtualWiki, topicName);
String html = "";
if (topic.getTopicType() == Topic.TYPE_FILE) {
// file, not an image
if (StringUtils.isBlank(caption)) {
caption = topicName.substring(NamespaceHandler.NAMESPACE_IMAGE.length() + 1);
}
String url = FilenameUtils.normalize(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH) + "/" + wikiFile.getUrl());
url = FilenameUtils.separatorsToUnix(url);
html += "<a href=\"" + url + "\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</a>";
return html;
}
WikiImage wikiImage = ImageUtil.initializeImage(wikiFile, maxDimension);
if (caption == null) {
caption = "";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "<div class=\"";
if (thumb || frame) {
html += "imgthumb ";
}
if (align != null && align.equalsIgnoreCase("left")) {
html += "imgleft ";
} else if (align != null && align.equalsIgnoreCase("center")) {
html += "imgcenter ";
} else if ((align != null && align.equalsIgnoreCase("right")) || thumb || frame) {
html += "imgright ";
} else {
// default alignment
html += "image ";
}
html = html.trim() + "\">";
}
if (wikiImage.getWidth() > 0) {
html += "<div style=\"width:" + (wikiImage.getWidth() + 2) + "px\">";
}
if (!suppressLink) {
html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
}
if (StringUtils.isBlank(style)) {
style = "wikiimg";
}
html += "<img class=\"" + style + "\" src=\"";
String url = new File(Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH), wikiImage.getUrl()).getPath();
url = FilenameUtils.separatorsToUnix(url);
html += url;
html += "\"";
html += " width=\"" + wikiImage.getWidth() + "\"";
html += " height=\"" + wikiImage.getHeight() + "\"";
html += " alt=\"" + StringEscapeUtils.escapeHtml(caption) + "\"";
html += " />";
if (!suppressLink) {
html += "</a>";
}
if (!StringUtils.isBlank(caption)) {
html += "<div class=\"imgcaption\">";
if (escapeHtml) {
html += StringEscapeUtils.escapeHtml(caption);
} else {
html += caption;
}
html += "</div>";
}
if (wikiImage.getWidth() > 0) {
html += "</div>";
}
if (frame || thumb || !StringUtils.isBlank(align)) {
html += "</div>";
}
return html;
}
|
diff --git a/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java b/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
index 0cfbcf1..0feaa90 100644
--- a/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
+++ b/db-util/storage/src/java/org/sakaiproject/util/BaseDbSingleStorage.java
@@ -1,1090 +1,1090 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.db.api.SqlReader;
import org.sakaiproject.db.api.SqlService;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.serialize.EntityParseException;
import org.sakaiproject.entity.api.serialize.EntityReader;
import org.sakaiproject.entity.api.serialize.EntityReaderHandler;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.time.cover.TimeService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <p>
* BaseDbSingleStorage is a class that stores Resources (of some type) in a database, <br />
* provides locked access, and generally implements a services "storage" class. The <br />
* service's storage class can extend this to provide covers to turn Resource and <br />
* Edit into something more type specific to the service.
* </p>
* <p>
* Note: the methods here are all "id" based, with the following assumptions: <br /> - just the Resource Id field is enough to distinguish one
* Resource from another <br /> - a resource's reference is based on no more than the resource id <br /> - a resource's id cannot change.
* </p>
* <p>
* In order to handle Unicode characters properly, the SQL statements executed by this class <br />
* should not embed Unicode characters into the SQL statement text; rather, Unicode values <br />
* should be inserted as fields in a PreparedStatement. Databases handle Unicode better in fields.
* </p>
*/
public class BaseDbSingleStorage implements DbSingleStorage
{
public static final String STORAGE_FIELDS = "XML";
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseDbSingleStorage.class);
/** Table name for resource records. */
protected String m_resourceTableName = null;
/** The field in the resource table that holds the resource id. */
protected String m_resourceTableIdField = null;
/** The additional field names in the resource table that go between the two ids and the xml */
protected String[] m_resourceTableOtherFields = null;
/** The xml tag name for the element holding each actual resource entry. */
protected String m_resourceEntryTagName = null;
/** If true, we do our locks in the remote database. */
protected boolean m_locksAreInDb = false;
/** If true, we do our locks in the remove database using a separate locking table. */
protected boolean m_locksAreInTable = true;
/** The StorageUser to callback for new Resource and Edit objects. */
protected StorageUser m_user = null;
/**
* Locks, keyed by reference, holding Connections (or, if locks are done locally, holding an Edit).
*/
protected Hashtable m_locks = null;
/** If set, we treat reasource ids as case insensitive. */
protected boolean m_caseInsensitive = false;
/** Injected (by constructor) SqlService. */
protected SqlService m_sql = null;
/** contains a map of the database dependent handlers. */
protected static Map<String, SingleStorageSql> databaseBeans;
/** The db handler we are using. */
protected SingleStorageSql singleStorageSql;
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#setDatabaseBeans(java.util.Map)
*/
public void setDatabaseBeans(Map databaseBeans)
{
this.databaseBeans = databaseBeans;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#setSingleStorageSql(java.lang.String)
*/
public void setSingleStorageSql(String vendor)
{
this.singleStorageSql = (databaseBeans.containsKey(vendor) ? databaseBeans.get(vendor) : databaseBeans.get("default"));
}
// since spring is not used and this class is instatiated directly, we need to "inject" these values ourselves
static
{
databaseBeans = new Hashtable<String, SingleStorageSql>();
databaseBeans.put("db2", new SingleStorageSqlDb2());
databaseBeans.put("default", new SingleStorageSqlDefault());
databaseBeans.put("hsql", new SingleStorageSqlHSql());
databaseBeans.put("mssql", new SingleStorageSqlMsSql());
databaseBeans.put("mysql", new SingleStorageSqlMySql());
databaseBeans.put("oracle", new SingleStorageSqlOracle());
}
/**
* Construct.
*
* @param resourceTableName
* Table name for resources.
* @param resourceTableIdField
* The field in the resource table that holds the id.
* @param resourceTableOtherFields
* The other fields in the resource table (between the two id and the xml fields).
* @param locksInDb
* If true, we do our locks in the remote database, otherwise we do them here.
* @param resourceEntryName
* The xml tag name for the element holding each actual resource entry.
* @param user
* The StorageUser class to call back for creation of Resource and Edit objects.
* @param sqlService
* The SqlService.
*/
public BaseDbSingleStorage(String resourceTableName, String resourceTableIdField, String[] resourceTableOtherFields, boolean locksInDb,
String resourceEntryName, StorageUser user, SqlService sqlService)
{
m_resourceTableName = resourceTableName;
m_resourceTableIdField = resourceTableIdField;
m_resourceTableOtherFields = resourceTableOtherFields;
m_locksAreInDb = locksInDb;
m_resourceEntryTagName = resourceEntryName;
m_user = user;
m_sql = sqlService;
setSingleStorageSql(m_sql.getVendor());
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#open()
*/
public void open()
{
// setup for locks
m_locks = new Hashtable();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#close()
*/
public void close()
{
if (!m_locks.isEmpty())
{
M_log.warn("close(): locks remain!");
// %%%
}
m_locks.clear();
m_locks = null;
}
/**
* Read one Resource from xml
*
* @param xml
* An string containing the xml which describes the resource.
* @return The Resource object created from the xml.
*/
protected Entity readResource(String xml)
{
try
{
if (m_user instanceof SAXEntityReader)
{
SAXEntityReader sm_user = (SAXEntityReader) m_user;
DefaultEntityHandler deh = sm_user.getDefaultHandler(sm_user
.getServices());
Xml.processString(xml, deh);
return deh.getEntity();
}
else
{
// read the xml
Document doc = Xml.readDocumentFromString(xml);
// verify the root element
Element root = doc.getDocumentElement();
if (!root.getTagName().equals(m_resourceEntryTagName))
{
M_log.warn("readResource(): not = " + m_resourceEntryTagName + " : "
+ root.getTagName());
return null;
}
// re-create a resource
Entity entry = m_user.newResource(null, root);
return entry;
}
}
catch (Exception e)
{
M_log.debug("readResource(): ", e);
return null;
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#checkResource(java.lang.String)
*/
public boolean checkResource(String id)
{
// just see if the record exists
String sql = singleStorageSql.getResourceIdSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(id);
List ids = m_sql.dbRead(sql, fields, null);
return (!ids.isEmpty());
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getResource(java.lang.String)
*/
public Entity getResource(String id)
{
Entity entry = null;
// get the user from the db
String sql = singleStorageSql.getXmlSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(id);
List xml = m_sql.dbRead(sql, fields, null);
if (!xml.isEmpty())
{
// create the Resource from the db xml
entry = readResource((String) xml.get(0));
}
return entry;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#isEmpty()
*/
public boolean isEmpty()
{
// count
int count = countAllResources();
return (count == 0);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResources()
*/
public List getAllResources()
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlSql(m_resourceTableName);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql);
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResources(int, int)
*/
public List getAllResources(int first, int last)
{
String sql = singleStorageSql.getXmlSql(m_resourceTableIdField, m_resourceTableName, first, last);
Object[] fields = singleStorageSql.getXmlFields(first, last);
List xml = m_sql.dbRead(sql, fields, null);
List rv = new Vector();
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) rv.add(entry);
}
}
return rv;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#countAllResources()
*/
public int countAllResources()
{
List all = new Vector();
// read all count
String sql = singleStorageSql.getNumRowsSql(m_resourceTableName);
List results = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
int count = result.getInt(1);
return new Integer(count);
}
catch (SQLException ignore)
{
return null;
}
}
});
if (results.isEmpty()) return 0;
return ((Integer) results.get(0)).intValue();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#countSelectedResourcesWhere(java.lang.String)
*/
public int countSelectedResourcesWhere(String sqlWhere)
{
List all = new Vector();
// read all where count
String sql = singleStorageSql.getNumRowsSql(m_resourceTableName, sqlWhere);
List results = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
int count = result.getInt(1);
return new Integer(count);
}
catch (SQLException ignore)
{
return null;
}
}
});
if (results.isEmpty()) return 0;
return ((Integer) results.get(0)).intValue();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResourcesWhere(java.lang.String, java.lang.String)
*/
public List getAllResourcesWhere(String field, String value)
{
// read all users from the db
String sql = singleStorageSql.getXmlSql(field, m_resourceTableName);
Object[] fields = new Object[1];
fields[0] = value;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
protected List loadResources(String sql, Object[] fields)
{
List all = m_sql.dbRead(sql, fields, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
// create the Resource from the db xml
String xml = result.getString(1);
Entity entry = readResource(xml);
return entry;
}
catch (SQLException ignore)
{
return null;
}
}
});
return all;
}
/**
* Get a limited number of Resources a given field matches a given value, returned in ascending order
* by another field. The limit on the number of rows is specified by values for the first item to be
* retrieved (indexed from 0) and the maxCount.
* @param selectBy The name of a field to be used in selecting resources.
* @param selectByValue The value to select.
* @param orderBy The name of a field to be used in ordering the resources.
* @param tableName The table on which the query is to operate
* @param first A non-negative integer indicating the first record to return
* @param maxCount A positive integer indicating the maximum number of rows to return
* @return The list of all Resources that meet the criteria.
*/
public List getAllResourcesWhere(String selectBy, String selectByValue, String orderBy, int first, int maxCount)
{
// read all users from the db
String sql = singleStorageSql.getXmlWhereLimitSql(selectBy, orderBy, m_resourceTableName, first, maxCount);
Object[] fields = new Object[1];
fields[0] = selectByValue;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getAllResourcesWhereLike(java.lang.String, java.lang.String)
*/
public List getAllResourcesWhereLike(String field, String value)
{
String sql = singleStorageSql.getXmlLikeSql(field, m_resourceTableName);
Object[] fields = new Object[1];
fields[0] = value;
// %%% + "order by " + m_resourceTableOrderField + " asc";
return loadResources(sql, fields);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getSelectedResources(org.sakaiproject.javax.Filter)
*/
public List getSelectedResources(final Filter filter)
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlAndFieldSql(m_resourceTableIdField, m_resourceTableName);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql, null, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
// read the id m_resourceTableIdField
String id = result.getString(1);
// read the xml
String xml = result.getString(2);
if (!filter.accept(caseId(id))) return null;
return xml;
}
catch (SQLException ignore)
{
return null;
}
}
});
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#getSelectedResourcesWhere(java.lang.String)
*/
public List getSelectedResourcesWhere(String sqlWhere)
{
List all = new Vector();
// read all users from the db
String sql = singleStorageSql.getXmlWhereSql(m_resourceTableName, sqlWhere);
// %%% + "order by " + m_resourceTableOrderField + " asc";
List xml = m_sql.dbRead(sql);
// process all result xml into user objects
if (!xml.isEmpty())
{
for (int i = 0; i < xml.size(); i++)
{
Entity entry = readResource((String) xml.get(i));
if (entry != null) all.add(entry);
}
}
return all;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#putResource(java.lang.String, java.lang.Object[])
*/
public Edit putResource(String id, Object[] others)
{
// create one with just the id, and perhaps some other fields as well
Entity entry = m_user.newResource(null, id, others);
// form the XML and SQL for the insert
Document doc = Xml.createDocument();
entry.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
String statement = // singleStorageSql.
"insert into " + m_resourceTableName + insertFields(m_resourceTableIdField, m_resourceTableOtherFields, "XML") + " values ( ?, "
+ valuesParams(m_resourceTableOtherFields) + " ? )";
Object[] flds = m_user.storageFields(entry);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 1, flds.length);
fields[0] = caseId(entry.getId());
fields[fields.length - 1] = xml;
// process the insert
boolean ok = m_sql.dbWrite(statement, fields);
// if this failed, assume a key conflict (i.e. id in use)
if (!ok) return null;
// now get a lock on the record for edit
Edit edit = editResource(id);
if (edit == null)
{
M_log.warn("putResource(): didn't get a lock!");
return null;
}
return edit;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#putDeleteResource(java.lang.String, java.lang.String, java.lang.String, java.lang.Object[])
*/
public Edit putDeleteResource(String id, String uuid, String userId, Object[] others)
{
Entity entry = m_user.newResource(null, id, others);
// form the XML and SQL for the insert
Document doc = Xml.createDocument();
entry.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
String statement = "insert into " + m_resourceTableName
+ insertDeleteFields(m_resourceTableIdField, m_resourceTableOtherFields, "RESOURCE_UUID", "DELETE_DATE", "DELETE_USERID", "XML")
+ " values ( ?, " + valuesParams(m_resourceTableOtherFields) + " ? ,? ,? ,?)";
Object[] flds = m_user.storageFields(entry);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 5];
System.arraycopy(flds, 0, fields, 1, flds.length);
fields[0] = caseId(entry.getId());
// uuid added here
fields[fields.length - 4] = uuid;
// date added here
fields[fields.length - 3] = TimeService.newTime();// .toStringLocalDate();
// userId added here
fields[fields.length - 2] = userId;
fields[fields.length - 1] = xml;
// process the insert
boolean ok = m_sql.dbWrite(statement, fields);
// if this failed, assume a key conflict (i.e. id in use)
if (!ok) return null;
// now get a lock on the record for edit
Edit edit = editResource(id);
if (edit == null)
{
M_log.warn("putResourceDelete(): didn't get a lock!");
return null;
}
return edit;
}
/** Construct the SQL statement */
protected String insertDeleteFields(String before, String[] fields, String uuid, String date, String userId, String after)
{
StringBuilder buf = new StringBuilder();
buf.append(" (");
buf.append(before);
buf.append(",");
if (fields != null)
{
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + ",");
}
}
buf.append(uuid);
buf.append(",");
buf.append(date);
buf.append(",");
buf.append(userId);
buf.append(",");
buf.append(after);
buf.append(")");
return buf.toString();
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#commitDeleteResource(org.sakaiproject.entity.api.Edit, java.lang.String)
*/
public void commitDeleteResource(Edit edit, String uuid)
{
// form the SQL statement and the var w/ the XML
Document doc = Xml.createDocument();
edit.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
Object[] flds = m_user.storageFields(edit);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 0, flds.length);
fields[fields.length - 2] = xml;
fields[fields.length - 1] = uuid;// caseId(edit.getId());
String statement = "update " + m_resourceTableName + " set " + updateSet(m_resourceTableOtherFields) + " XML = ? where ( RESOURCE_UUID = ? )";
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("commitResource(): edit not in locks");
return;
}
// update, commit, release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// remove the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the update
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("commit: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// just process the update
m_sql.dbWrite(statement, fields);
// remove the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#editResource(java.lang.String)
*/
public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
- sessionId = "";
+ sessionId = ""; // TODO - "" gets converted to a null and will never be able to be cleaned up -AZ (SAK-11841)
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#commitResource(org.sakaiproject.entity.api.Edit)
*/
public void commitResource(Edit edit)
{
// form the SQL statement and the var w/ the XML
Document doc = Xml.createDocument();
edit.toXml(doc, new Stack());
String xml = Xml.writeDocumentToString(doc);
Object[] flds = m_user.storageFields(edit);
if (flds == null) flds = new Object[0];
Object[] fields = new Object[flds.length + 2];
System.arraycopy(flds, 0, fields, 0, flds.length);
fields[fields.length - 2] = xml;
fields[fields.length - 1] = caseId(edit.getId());
String statement = "update " + m_resourceTableName + " set " + updateSet(m_resourceTableOtherFields) + " XML = ? where ( "
+ m_resourceTableIdField + " = ? )";
// singleStorageSql.getUpdateXml(m_resourceTableIdField, m_resourceTableOtherFields, m_resourceTableName);
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("commitResource(): edit not in locks");
return;
}
// update, commit, release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// remove the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the update
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("commit: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// just process the update
m_sql.dbWrite(statement, fields);
// remove the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#cancelResource(org.sakaiproject.entity.api.Edit)
*/
public void cancelResource(Edit edit)
{
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("cancelResource(): edit not in locks");
return;
}
// rollback and release the lock's connection
m_sql.dbCancel(lock);
// release the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// remove the lock
String statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("cancel: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// release the lock
m_locks.remove(edit.getReference());
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.DbSingleStorage#removeResource(org.sakaiproject.entity.api.Edit)
*/
public void removeResource(Edit edit)
{
// form the SQL delete statement
String statement = singleStorageSql.getDeleteSql(m_resourceTableIdField, m_resourceTableName);
Object fields[] = new Object[1];
fields[0] = caseId(edit.getId());
if (m_locksAreInDb)
{
// use this connection that is stored with the lock
Connection lock = (Connection) m_locks.get(edit.getReference());
if (lock == null)
{
M_log.warn("removeResource(): edit not in locks");
return;
}
// process the delete statement, commit, and release the lock's connection
m_sql.dbUpdateCommit(statement, fields, null, lock);
// release the lock
m_locks.remove(edit.getReference());
}
else if (m_locksAreInTable)
{
// process the delete statement
m_sql.dbWrite(statement, fields);
// remove the lock
statement = singleStorageSql.getDeleteLocksSql();
// collect the fields
Object lockFields[] = new Object[2];
lockFields[0] = m_resourceTableName;
lockFields[1] = internalRecordId(caseId(edit.getId()));
boolean ok = m_sql.dbWrite(statement, lockFields);
if (!ok)
{
M_log.warn("remove: missing lock for table: " + lockFields[0] + " key: " + lockFields[1]);
}
}
else
{
// process the delete statement
m_sql.dbWrite(statement, fields);
// release the lock
m_locks.remove(edit.getReference());
}
}
/**
* Form a string of n question marks with commas, for sql value statements, one for each item in the values array, or an empty string if null.
*
* @param values
* The values to be inserted into the sql statement.
* @return A sql statement fragment for the values part of an insert, one for each value in the array.
*/
protected String valuesParams(String[] fields)
{
if ((fields == null) || (fields.length == 0)) return "";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < fields.length; i++)
{
buf.append(" ?,");
}
return buf.toString();
}
/**
* Form a string of n name=?, for sql update set statements, one for each item in the values array, or an empty string if null.
*
* @param values
* The values to be inserted into the sql statement.
* @return A sql statement fragment for the values part of an insert, one for each value in the array.
*/
protected String updateSet(String[] fields)
{
if ((fields == null) || (fields.length == 0)) return "";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + " = ?,");
}
return buf.toString();
}
/**
* Form a string of (field, field, field), for sql insert statements, one for each item in the fields array, plus one before, and one after.
*
* @param before
* The first field name.
* @param values
* The extra field names, in the middle.
* @param after
* The last field name.
* @return A sql statement fragment for the insert fields.
*/
protected String insertFields(String before, String[] fields, String after)
{
StringBuilder buf = new StringBuilder();
buf.append(" (");
buf.append(before);
buf.append(",");
if (fields != null)
{
for (int i = 0; i < fields.length; i++)
{
buf.append(fields[i] + ",");
}
}
buf.append(after);
buf.append(")");
return buf.toString();
}
/**
* Fix the case of resource ids to support case insensitive ids if enabled
*
* @param The
* id to fix.
* @return The id, case modified as needed.
*/
protected String caseId(String id)
{
if (m_caseInsensitive)
{
return id.toLowerCase();
}
return id;
}
/**
* Enable / disable case insensitive ids.
*
* @param setting
* true to set case insensitivity, false to set case sensitivity.
*/
protected void setCaseInsensitivity(boolean setting)
{
m_caseInsensitive = setting;
}
/**
* Return a record ID to use internally in the database. This is needed for databases (MySQL) that have limits on key lengths. The hash code
* ensures that the record ID will be unique, even if the DB only considers a prefix of a very long record ID.
*
* @param recordId
* @return The record ID to use internally in the database
*/
private String internalRecordId(String recordId)
{
if ("mysql".equals(m_sql.getVendor()))
{
if (recordId == null) recordId = "null";
return recordId.hashCode() + " - " + recordId;
}
else
// oracle, hsqldb
{
return recordId;
}
}
}
| true | true | public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
sessionId = "";
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
| public Edit editResource(String id)
{
Edit edit = null;
if (m_locksAreInDb)
{
if ("oracle".equals(m_sql.getVendor()))
{
// read the record and get a lock on it (non blocking)
String statement = "select XML from " + m_resourceTableName + " where ( " + m_resourceTableIdField + " = '"
+ Validator.escapeSql(caseId(id)) + "' )" + " for update nowait";
StringBuilder result = new StringBuilder();
Connection lock = m_sql.dbReadLock(statement, result);
// for missing or already locked...
if ((lock == null) || (result.length() == 0)) return null;
// make first a Resource, then an Edit
Entity entry = readResource(result.toString());
edit = m_user.newResourceEdit(null, entry);
// store the lock for this object
m_locks.put(entry.getReference(), lock);
}
else
{
throw new UnsupportedOperationException("Record locking only available when configured with Oracle database");
}
}
// if the locks are in a separate table in the db
else if (m_locksAreInTable)
{
// read the record - fail if not there
Entity entry = getResource(id);
if (entry == null) return null;
// write a lock to the lock table - if we can do it, we get the lock
String statement = singleStorageSql.getInsertLocks();
// we need session id and user id
String sessionId = UsageSessionService.getSessionId();
if (sessionId == null)
{
sessionId = ""; // TODO - "" gets converted to a null and will never be able to be cleaned up -AZ (SAK-11841)
}
// collect the fields
Object fields[] = new Object[4];
fields[0] = m_resourceTableName;
fields[1] = internalRecordId(caseId(id));
fields[2] = TimeService.newTime();
fields[3] = sessionId;
// add the lock - if fails, someone else has the lock
boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
if (!ok)
{
return null;
}
// we got the lock! - make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
}
// otherwise, get the lock locally
else
{
// get the entry, and check for existence
Entity entry = getResource(id);
if (entry == null) return null;
// we only sync this getting - someone may release a lock out of sync
synchronized (m_locks)
{
// if already locked
if (m_locks.containsKey(entry.getReference())) return null;
// make the edit from the Resource
edit = m_user.newResourceEdit(null, entry);
// store the edit in the locks by reference
m_locks.put(entry.getReference(), edit);
}
}
return edit;
}
|
diff --git a/src/gui/ImportSessionsForm.java b/src/gui/ImportSessionsForm.java
index 936d6ea..b7aae60 100644
--- a/src/gui/ImportSessionsForm.java
+++ b/src/gui/ImportSessionsForm.java
@@ -1,244 +1,244 @@
/* This file is part of "MidpSSH".
* Copyright (c) 2005 Karl von Randow.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package gui;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import app.LineInputStream;
import app.Main;
import app.SessionManager;
import app.SessionSpec;
import app.Settings;
/**
* Import sessions using an HTTP connection. Parses the returned page looking for lines of the form:
* ssh username@hostname[:port] alias
* telnet hostname[:port] alias
* @author Karl
*
*/
public class ImportSessionsForm extends Form implements Activatable, Runnable, CommandListener {
private TextField tfUrl;
private Activatable back;
//#ifdef blackberryconntypes
private ChoiceGroup cgBlackberryConnType;
//#endif
/**
* @param title
* @param text
* @param maxSize
* @param constraints
*/
public ImportSessionsForm() {
super("Import Sessions");
tfUrl = new TextField( "URL:", null, 255, TextField.ANY );
//#ifdef midp2
tfUrl.setConstraints(TextField.ANY | TextField.URL);
//#endif
append(tfUrl);
//#ifdef blackberryconntypes
cgBlackberryConnType = new ChoiceGroup( "Connection Type", ChoiceGroup.EXCLUSIVE);
cgBlackberryConnType.append( "Default", null );
cgBlackberryConnType.append( "TCP/IP", null );
cgBlackberryConnType.append( "BES", null );
append(cgBlackberryConnType);
//#endif
addCommand(MessageForm.okCommand);
addCommand(MessageForm.backCommand);
setCommandListener(this);
}
public void commandAction(Command command, Displayable arg1) {
if (command == MessageForm.okCommand) {
new Thread(this).start();
}
else if (command == MessageForm.backCommand) {
if (back != null) {
back.activate();
}
}
}
public void activate() {
Main.setDisplay(this);
}
public void activate(Activatable back) {
this.back = back;
activate();
}
public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
- throw new IOException("HTTP response code: " + rc);
+ throw new IOException("HTTP " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
private void appendOrReplaceSession(SessionSpec newSpec) {
SessionSpec spec = null;
int replaceAt = -1;
Vector sessions = SessionManager.getSessions();
for (int i = 0; i < sessions.size(); i++) {
spec = (SessionSpec) sessions.elementAt(i);
if (spec.type.equals(newSpec.type)) {
if (newSpec.alias.equals(spec.alias)) {
/* Replace this one */
replaceAt = i;
break;
}
}
}
if (replaceAt == -1) {
SessionManager.addSession(newSpec);
}
else {
spec.alias = newSpec.alias;
spec.username = newSpec.username;
spec.host = newSpec.host;
SessionManager.replaceSession(replaceAt, spec);
}
}
}
| true | true | public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
| public void run() {
HttpConnection c = null;
LineInputStream in = null;
try {
int imported = 0;
String url = tfUrl.getString();
//#ifdef blackberryconntypes
if (cgBlackberryConnType.getSelectedIndex() == 1) {
url += ";deviceside=true";
}
else if (cgBlackberryConnType.getSelectedIndex() == 2) {
url += ";deviceside=false";
}
//#endif
//#ifdef blackberryenterprise
url += ";deviceside=false";
//#endif
c = (HttpConnection) Connector.open(url);
int rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP " + rc);
}
in = new LineInputStream(c.openInputStream());
String line = in.readLine();
while (line != null) {
String username = "", host = null, alias = "";
SessionSpec spec = null;
if (line.startsWith("ssh ")) {
int soh = 4;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
int at = line.indexOf('@', soh);
if (at != -1 && at < eoh) {
/* Contains username */
username = line.substring(soh, at);
soh = at + 1;
}
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_SSH;
}
}
else if (line.startsWith("telnet ")) {
int soh = 7;
int eoh = line.indexOf(' ', soh);
if (eoh != -1) {
host = line.substring(soh, eoh);
alias = line.substring(eoh + 1).trim();
/* Insert or replace in Sessions list */
spec = new SessionSpec();
spec.type = SessionSpec.TYPE_TELNET;
}
}
if (spec != null) {
/* Insert or replace in Sessions list */
spec.alias = alias;
spec.host = host;
spec.username = username;
spec.password = "";
appendOrReplaceSession(spec);
imported++;
}
line = in.readLine();
}
back.activate();
Settings.sessionsImportUrl = url;
Settings.saveSettings();
Alert alert = new Alert( "Import Complete" );
alert.setType( AlertType.INFO );
alert.setString( "Imported " + imported + " sessions" );
Main.alert(alert, (Displayable)back);
}
catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert( "Import Failed" );
alert.setType( AlertType.ERROR );
alert.setString( e.getMessage() );
alert.setTimeout( Alert.FOREVER );
Main.alert(alert, this);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (c != null) {
try {
c.close();
} catch (IOException e1) {
}
}
}
}
|
diff --git a/src/org/ohmage/feedback/FeedbackService.java b/src/org/ohmage/feedback/FeedbackService.java
index 91bf2e6..9ae019c 100644
--- a/src/org/ohmage/feedback/FeedbackService.java
+++ b/src/org/ohmage/feedback/FeedbackService.java
@@ -1,335 +1,338 @@
package org.ohmage.feedback;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.OhmageApi;
import org.ohmage.SharedPreferencesHelper;
import org.ohmage.OhmageApi.ImageReadResponse;
import org.ohmage.OhmageApi.Result;
import org.ohmage.OhmageApi.SurveyReadResponse;
import org.ohmage.db.Campaign;
import org.ohmage.db.DbHelper;
import org.ohmage.prompt.photo.PhotoPrompt;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import edu.ucla.cens.systemlog.Log;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class FeedbackService extends WakefulIntentService {
private static final String TAG = "FeedbackService";
public FeedbackService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
}
@SuppressWarnings("unchecked")
@Override
protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
- campaigns = new ArrayList<Campaign>(1);
- campaigns.add(dbHelper.getCampaign(intent.getStringExtra("campaign_urn")));
+ // the campaign object we create only inclues the mUrn field since we don't have anything else
+ campaigns = new ArrayList<Campaign>();
+ Campaign candidate = new Campaign();
+ candidate.mUrn = intent.getStringExtra("campaign_urn");
+ campaigns.add(candidate);
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
public static boolean ensurePhotoExists(Context context, String campaignUrn, String photoUUID) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + campaignUrn.replace(':', '_'));
photoDir.mkdirs();
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
// assemble all the resources to connect to the server
// and then do so!
OhmageApi api = new OhmageApi(context);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(context);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", campaignUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
return true; // we downloaded it successfuly
}
else
return false; // we were unable to download it for some reason
}
catch (IOException e) {
return false; // something went wrong while downloading it
}
}
return true; // it was already there!
}
}
| true | true | protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
campaigns = new ArrayList<Campaign>(1);
campaigns.add(dbHelper.getCampaign(intent.getStringExtra("campaign_urn")));
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
| protected void doWakefulWork(Intent intent) {
// for the time being, we just pull all the surveys and update our feedback cache with them
// FIXME: in the future, we should only download what we need...two strategies for that:
// 1) maintain a timestamp of the most recent refresh and request only things after it
// 2) somehow figure out which surveys the server has and we don't via the hashcode and sync accordingly
Log.v(TAG, "Feedback service starting");
OhmageApi api = new OhmageApi(this);
SharedPreferencesHelper prefs = new SharedPreferencesHelper(this);
String username = prefs.getUsername();
String hashedPassword = prefs.getHashedPassword();
// helper instance for parsing utc timestamps
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
// get the time since the last refresh so we can retrieve entries only since then.
// also save the time of this refresh, but only put it into the prefs at the end
long lastRefresh = prefs.getLastFeedbackRefreshTimestamp();
long thisRefresh = System.currentTimeMillis();
// opening two databases here:
// the standard db which lists the users' campaigns...
DbHelper dbHelper = new DbHelper(this);
List<Campaign> campaigns = dbHelper.getCampaigns();
// ...and the feedback database into which we'll be inserting their responses (if necessary)
FeedbackDatabase fbDB = new FeedbackDatabase(this);
if (intent.hasExtra("campaign_urn")) {
// if we received a campaign_urn in the intent, only download the data for that one
// the campaign object we create only inclues the mUrn field since we don't have anything else
campaigns = new ArrayList<Campaign>();
Campaign candidate = new Campaign();
candidate.mUrn = intent.getStringExtra("campaign_urn");
campaigns.add(candidate);
}
else {
// otherwise, do all the campaigns
campaigns = dbHelper.getCampaigns();
}
// we'll have to iterate through all the campaigns in which this user
// is participating in order to gather all of their data
for (Campaign c : campaigns) {
Log.v(TAG, "Requesting responsese for campaign " + c.mUrn + "...");
// attempt to construct a date range on which to query, if one exists
// this will be from the last refresh to next year, in order to get everything
String startDate = null;
String endDate = null;
// disabled for now b/c it's going to be hard to test
/*
if (lastRefresh > 0) {
Date future = new Date();
future.setYear(future.getYear()+1);
startDate = ISO8601Utilities.formatDateTime(new Date(lastRefresh));
endDate = ISO8601Utilities.formatDateTime(future);
}
*/
SurveyReadResponse apiResponse = api.surveyResponseRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, null, null, "json-rows", startDate, endDate);
// check if it was successful or not
String error = null;
switch (apiResponse.getResult()) {
case FAILURE: error = "survey response query failed"; break;
case HTTP_ERROR: error = "http error during request"; break;
case INTERNAL_ERROR: error = "internal error during request"; break;
}
if (error != null) {
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return;
}
Log.v(TAG, "Request for campaign " + c.mUrn + " complete!");
// gather our survey response array from the response
JSONArray data = apiResponse.getData();
// also maintain a list of photo UUIDs that may or may not be on the device
// this is campaign-specific, which is why it's happening in this loop over the campaigns
ArrayList<String> photoUUIDs = new ArrayList<String>();
// if they have nothing on the server, data may be null
// if that's the case, don't do anything
if (data == null) {
Log.v(TAG, "No data to process, continuing feedback service");
return;
}
// for each survey, insert a record into our feedback db
// if we're unable to insert, just continue (likely a duplicate)
// also, note the schema follows the definition in the documentation
for (int i = 0; i < data.length(); ++i) {
Log.v(TAG, "Processing record " + (i+1) + "/" + data.length());
try {
JSONObject survey = data.getJSONObject(i);
// first we need to gather all of the appropriate data
// from the survey response. some of this data needs to
// be transformed to match the format that SurveyActivity
// uploads/broadcasts, since our survey responses can come
// from either source and need to be stored the same way.
String date = survey.getString("timestamp");
String timezone = survey.getString("timezone");
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
long time = sdf.parse(date).getTime();
// much of the location data is optional, hence the "opt*()" calls
String locationStatus = survey.getString("location_status");
double locationLatitude = survey.optDouble("latitude");
double locationLongitude = survey.optDouble("longitude");
String locationProvider = survey.optString("location_provider");
float locationAccuracy = (float)survey.optDouble("location_accuracy");
long locationTime = survey.optLong("location_timestamp");
String surveyId = survey.getString("survey_id");
String surveyLaunchContext = survey.getString("launch_context_long").toString();
// we need to parse out the responses and put them in
// the same format as what we collect from the local activity
JSONObject inputResponses = survey.getJSONObject("responses");
// iterate through inputResponses and create a new JSON object of prompt_ids and values
JSONArray responseJson = new JSONArray();
Iterator<String> keys = inputResponses.keys();
while (keys.hasNext()) {
// for each prompt response, create an object with a prompt_id/value pair
// FIXME: ignoring the "custom_fields" field for now, since it's unused
String key = keys.next();
JSONObject curItem = inputResponses.getJSONObject(key);
// FIXME: deal with repeatable sets here someday, although i'm not sure how
// how do we visualize them on a line graph along with regular points? scatter chart?
if (curItem.has("prompt_response")) {
JSONObject newItem = new JSONObject();
try {
String value = curItem.getString("prompt_response");
newItem.put("prompt_id", key);
newItem.put("value", value);
// if it's a photo, put its value (the photo's UUID) into the photoUUIDs list
if (curItem.getString("prompt_type").equalsIgnoreCase("photo") && !value.equalsIgnoreCase("NOT_DISPLAYED")) {
photoUUIDs.add(value);
}
} catch (JSONException e) {
Log.e(TAG, "JSONException when trying to generate response json", e);
throw new RuntimeException(e);
}
responseJson.put(newItem);
}
}
// render it to a string for storage into our db
String response = responseJson.toString();
// ok, gathered everything; time to insert into the feedback DB
// note that we mark this entry as "remote", meaning it came from the server
fbDB.addResponseRow(
c.mUrn,
username,
date,
time,
timezone,
locationStatus,
locationLatitude,
locationLongitude,
locationProvider,
locationAccuracy,
locationTime,
surveyId,
surveyLaunchContext,
response,
"remote");
// it's possible that the above will fail, in which case it silently returns -1
// we don't do anything differently in that case, so there's no need to check
}
catch(ParseException e) {
// this is a date parse exception, likely thrown from where we parse the utc timestamp
Log.e(TAG, "Problem parsing survey response timestamp", e);
return;
}
catch (JSONException e) {
Log.e(TAG, "Problem parsing response json", e);
return;
}
}
// now that we're done inserting all that data from the server
// let's see if we already have all the photos that were mentioned in the responses
/*
if (photoUUIDs.size() > 0) {
// get the image directory for this campaign and ensure it exists
File photoDir = new File(PhotoPrompt.IMAGE_PATH + "/" + c.mUrn.replace(':', '_'));
photoDir.mkdirs();
for (String photoUUID : photoUUIDs) {
// check if it doesn't already exist in our photos directory
File photo = new File(photoDir, photoUUID + ".jpg");
Log.v(TAG, "Checking photo w/UUID " + photoUUID + "...");
if (!photo.exists()) {
// it doesn't exist, so we have to download it :(
ImageReadResponse ir = api.imageRead(SharedPreferencesHelper.DEFAULT_SERVER_URL, username, hashedPassword, "android", c.mUrn, username, photoUUID, null);
// if it succeeded, it contains data that we should save as the photo file above
try {
if (ir != null && ir.getResult() == Result.SUCCESS) {
photo.createNewFile();
FileOutputStream photoWriter = new FileOutputStream(photo);
photoWriter.write(ir.getData());
photoWriter.close();
Log.v(TAG, "Downloaded photo w/UUID " + photoUUID);
}
else
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID + ": " + ir.getResult().toString());
}
catch (IOException e) {
Log.e(TAG, "Unable to save photo w/UUID " + photoUUID, e);
return;
}
}
else
Log.v(TAG, "Photo w/UUID " + photoUUID + " already exists");
}
}
*/
// done with this campaign! on to the next one...
}
// once we're completely done, it's safe to store the time at which this refresh happened.
// this is to ensure that we don't incorrectly flag the range between the last and current
// as completed in the case that there's an error mid-way through.
prefs.putLastFeedbackRefreshTimestamp(thisRefresh);
Log.v(TAG, "Feedback service complete");
}
|
diff --git a/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java b/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
index 667d86bc2..7da35ce27 100644
--- a/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
+++ b/src/main/java/com/google/gerrit/client/patches/UnifiedDiffTable.java
@@ -1,347 +1,347 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.patches;
import static com.google.gerrit.client.patches.PatchLine.Type.CONTEXT;
import static com.google.gerrit.client.patches.PatchLine.Type.DELETE;
import static com.google.gerrit.client.patches.PatchLine.Type.INSERT;
import com.google.gerrit.client.data.EditList;
import com.google.gerrit.client.data.PatchScript;
import com.google.gerrit.client.data.SparseFileContent;
import com.google.gerrit.client.data.EditList.Hunk;
import com.google.gerrit.client.data.PatchScript.DisplayMethod;
import com.google.gerrit.client.reviewdb.Patch;
import com.google.gerrit.client.reviewdb.PatchLineComment;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.safehtml.client.PrettyFormatter;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import com.google.gwtorm.client.KeyUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class UnifiedDiffTable extends AbstractPatchContentTable {
private static final int PC = 3;
private static final Comparator<PatchLineComment> BY_DATE =
new Comparator<PatchLineComment>() {
public int compare(final PatchLineComment o1, final PatchLineComment o2) {
return o1.getWrittenOn().compareTo(o2.getWrittenOn());
}
};
@Override
protected void onCellDoubleClick(final int row, final int column) {
if (getRowItem(row) instanceof PatchLine) {
final PatchLine pl = (PatchLine) getRowItem(row);
switch (pl.getType()) {
case DELETE:
case CONTEXT:
createCommentEditor(row + 1, PC, pl.getLineA(), (short) 0);
break;
case INSERT:
createCommentEditor(row + 1, PC, pl.getLineB(), (short) 1);
break;
}
}
}
@Override
protected void onInsertComment(final PatchLine pl) {
final int row = getCurrentRow();
switch (pl.getType()) {
case DELETE:
case CONTEXT:
createCommentEditor(row + 1, PC, pl.getLineA(), (short) 0);
break;
case INSERT:
createCommentEditor(row + 1, PC, pl.getLineB(), (short) 1);
break;
}
}
private void appendImgTag(SafeHtmlBuilder nc, String url) {
nc.openElement("img");
nc.setAttribute("src", url);
nc.closeElement("img");
}
@Override
protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
+ appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
+ } else {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
- } else {
- appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
@Override
public void display(final CommentDetail cd) {
if (cd.isEmpty()) {
return;
}
setAccountInfoCache(cd.getAccounts());
final ArrayList<PatchLineComment> all = new ArrayList<PatchLineComment>();
for (int row = 0; row < table.getRowCount();) {
if (getRowItem(row) instanceof PatchLine) {
final PatchLine pLine = (PatchLine) getRowItem(row);
final List<PatchLineComment> fora = cd.getForA(pLine.getLineA());
final List<PatchLineComment> forb = cd.getForB(pLine.getLineB());
row++;
if (!fora.isEmpty() && !forb.isEmpty()) {
all.clear();
all.addAll(fora);
all.addAll(forb);
Collections.sort(all, BY_DATE);
row = insert(all, row);
} else if (!fora.isEmpty()) {
row = insert(fora, row);
} else if (!forb.isEmpty()) {
row = insert(forb, row);
}
} else {
row++;
}
}
}
private int insert(final List<PatchLineComment> in, int row) {
for (Iterator<PatchLineComment> ci = in.iterator(); ci.hasNext();) {
final PatchLineComment c = ci.next();
table.insertRow(row);
table.getCellFormatter().setStyleName(row, 0, S_ICON_CELL);
bindComment(row, PC, c, !ci.hasNext());
row++;
}
return row;
}
private void appendFileHeader(final SafeHtmlBuilder m, final String line) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-FILE_HEADER");
m.append(line);
m.closeTd();
closeLine(m);
}
private void appendHunkHeader(final SafeHtmlBuilder m, final Hunk hunk) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-HUNK_HEADER");
m.append("@@ -");
appendRange(m, hunk.getCurA() + 1, hunk.getEndA() - hunk.getCurA());
m.append(" +");
appendRange(m, hunk.getCurB() + 1, hunk.getEndB() - hunk.getCurB());
m.append(" @@");
m.closeTd();
closeLine(m);
}
private void appendRange(final SafeHtmlBuilder m, final int begin,
final int cnt) {
switch (cnt) {
case 0:
m.append(begin - 1);
m.append(",0");
break;
case 1:
m.append(begin);
break;
default:
m.append(begin);
m.append(',');
m.append(cnt);
break;
}
}
private void appendLineText(final SafeHtmlBuilder m,
final PatchLine.Type type, final SparseFileContent src, final int i,
final PrettyFormatter fmtA, final PrettyFormatter fmtB) {
final String text = src.get(i);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-" + type.name());
switch (type) {
case CONTEXT:
m.nbsp();
m.append(fmtA.format(text));
fmtB.update(text);
break;
case DELETE:
m.append("-");
m.append(fmtA.format(text));
break;
case INSERT:
m.append("+");
m.append(fmtB.format(text));
break;
}
m.closeTd();
}
private void appendNoLF(final SafeHtmlBuilder m) {
openLine(m);
padLineNumber(m);
padLineNumber(m);
m.openTd();
m.addStyleName("DiffText");
m.addStyleName("DiffText-NO_LF");
m.append("\\ No newline at end of file");
m.closeTd();
closeLine(m);
}
private void openLine(final SafeHtmlBuilder m) {
m.openTr();
m.setAttribute("valign", "top");
m.openTd();
m.setStyleName(S_ICON_CELL);
m.closeTd();
}
private void closeLine(final SafeHtmlBuilder m) {
m.closeTr();
}
private void padLineNumber(final SafeHtmlBuilder m) {
m.openTd();
m.setStyleName("LineNumber");
m.closeTd();
}
private void appendLineNumber(final SafeHtmlBuilder m, final int idx) {
m.openTd();
m.setStyleName("LineNumber");
m.append(idx + 1);
m.closeTd();
}
}
| false | true | protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
} else {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
| protected void render(final PatchScript script) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
final SafeHtmlBuilder nc = new SafeHtmlBuilder();
final PrettyFormatter fmtA = PrettyFormatter.newFormatter(formatLanguage);
final PrettyFormatter fmtB = PrettyFormatter.newFormatter(formatLanguage);
fmtB.setShowWhiteSpaceErrors(true);
// Display the patch header
for (final String line : script.getPatchHeader()) {
appendFileHeader(nc, line);
}
if (script.getDisplayMethodA() == DisplayMethod.IMG
|| script.getDisplayMethodB() == DisplayMethod.IMG) {
final String rawBase = GWT.getHostPageBaseURL() + "cat/";
nc.openTr();
nc.setAttribute("valign", "center");
nc.setAttribute("align", "center");
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
nc.nbsp();
nc.closeTd();
nc.openTd();
if (script.getDisplayMethodA() == DisplayMethod.IMG) {
if (idSideA == null) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^1");
} else {
Patch.Key k = new Patch.Key(idSideA, patchKey.get());
appendImgTag(nc, rawBase + KeyUtil.encode(k.toString()) + "^0");
}
}
if (script.getDisplayMethodB() == DisplayMethod.IMG) {
appendImgTag(nc, rawBase + KeyUtil.encode(patchKey.toString()) + "^0");
}
nc.closeTd();
nc.closeTr();
}
final ArrayList<PatchLine> lines = new ArrayList<PatchLine>();
for (final EditList.Hunk hunk : script.getHunks()) {
appendHunkHeader(nc, hunk);
while (hunk.next()) {
if (hunk.isContextLine()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, CONTEXT, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incBoth();
lines.add(new PatchLine(CONTEXT, hunk.getCurA(), hunk.getCurB()));
} else if (hunk.isDeletedA()) {
openLine(nc);
appendLineNumber(nc, hunk.getCurA());
padLineNumber(nc);
appendLineText(nc, DELETE, a, hunk.getCurA(), fmtA, fmtB);
closeLine(nc);
hunk.incA();
lines.add(new PatchLine(DELETE, hunk.getCurA(), 0));
if (a.size() == hunk.getCurA() && a.isMissingNewlineAtEnd())
appendNoLF(nc);
} else if (hunk.isInsertedB()) {
openLine(nc);
padLineNumber(nc);
appendLineNumber(nc, hunk.getCurB());
appendLineText(nc, INSERT, b, hunk.getCurB(), fmtA, fmtB);
closeLine(nc);
hunk.incB();
lines.add(new PatchLine(INSERT, 0, hunk.getCurB()));
if (b.size() == hunk.getCurB() && b.isMissingNewlineAtEnd())
appendNoLF(nc);
}
}
}
resetHtml(nc);
initScript(script);
int row = script.getPatchHeader().size();
final CellFormatter fmt = table.getCellFormatter();
final Iterator<PatchLine> iLine = lines.iterator();
while (iLine.hasNext()) {
final PatchLine l = iLine.next();
final String n = "DiffText-" + l.getType().name();
while (!fmt.getStyleName(row, PC).contains(n)) {
row++;
}
setRowItem(row++, l);
}
}
|
diff --git a/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java b/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
index 136a4bb..a17e9d5 100644
--- a/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
+++ b/src/main/java/com/theminequest/api/quest/event/TargetedQuestEvent.java
@@ -1,42 +1,42 @@
package com.theminequest.api.quest.event;
import java.util.Collection;
import java.util.Map;
import com.theminequest.api.CompleteStatus;
import com.theminequest.api.platform.entity.MQPlayer;
import com.theminequest.api.quest.QuestDetails;
import com.theminequest.api.targeted.QuestTarget;
public abstract class TargetedQuestEvent extends DelayedQuestEvent {
private int targetID;
private long delayMS;
public final void setupTarget(int targetID, long delayMS) {
this.targetID = targetID;
this.delayMS = delayMS;
}
@Override
public final long getDelay() {
return delayMS;
}
@Override
public final boolean delayedConditions() {
return true;
}
@Override
public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
- throw new RuntimeException("No such target ID!");
+ throw new RuntimeException("No such target ID " + targetID + "...");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
public abstract CompleteStatus targetAction(Collection<MQPlayer> entities);
}
| true | true | public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
throw new RuntimeException("No such target ID!");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
| public final CompleteStatus action() {
Map<Integer, QuestTarget> targetMap = getQuest().getDetails().getProperty(QuestDetails.QUEST_TARGET);
if (!targetMap.containsKey(targetID))
throw new RuntimeException("No such target ID " + targetID + "...");
QuestTarget t = targetMap.get(targetID);
return targetAction(t.getPlayers(getQuest()));
}
|
diff --git a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
index 38b91415d..7bc576fe5 100644
--- a/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
+++ b/src/contributions/resources/search/src/java/org/wyona/yanel/impl/resources/search/ReindexResource.java
@@ -1,124 +1,124 @@
/*
* Copyright 2011 Wyona
*/
package org.wyona.yanel.impl.resources.search;
import org.wyona.yarep.util.YarepUtil;
import org.wyona.yarep.core.Repository;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;
/**
* Re-indexing resource. This resource can be used to start the re-indexing
* process of an arbitrary repository from within a browser session. If you
* configure this resource in your realm, make sure to protect it because you
* most likely don't want your users to start re-indexing processes.
*/
public class ReindexResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(ReindexResource.class);
private static String REPO_NAME = "repository";
private static String REINDEX_XMLNS = "http://www.wyona.org/yanel/reindex/1.0";
/**
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
- sb.append("<r:selected-repository id=\"" + repo.getID() + "\">" + repo.getName() + "</r:selected-repository>");
+ sb.append("<r:selected-repository id=\"" + reindexRepo + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
}
| true | true | protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
sb.append("<r:selected-repository id=\"" + repo.getID() + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
| protected InputStream getContentXML(String viewId) throws Exception {
// Build output document
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<r:reindex xmlns:r=\"");
sb.append(REINDEX_XMLNS);
sb.append("\">");
// Which repo needs to be re-indexed?
String reindexRepo = getEnvironment().getRequest().getParameter(REPO_NAME);
// Are we allowed to re-index this repository?
// Only default repositories and the ones listed in the resource configuration are allowed to be re-indexed
boolean allowed = false;
// List default repositories
// Only show them if we're allowed to re-index them
String defaultRepos = getResourceConfigProperty("allow-default-repos");
if("true".equals(defaultRepos)) {
sb.append("<r:repository id=\"yanel_data\">Realm's data repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-identities\">Realm's ac-identities repository</r:repository>");
sb.append("<r:repository id=\"yanel_ac-policies\">Realm's ac-policies repository</r:repository>");
sb.append("<r:repository id=\"yanel_res-configs\">Realm's res-configs repository</r:repository>");
}
// List extra repositories from repo configuration
String[] repoIds = getResourceConfigProperties("repository-id");
for(String repoId : repoIds) {
if(repoId != null && !"".equals(repoId)) {
sb.append("<r:repository id=\"");
sb.append(repoId);
sb.append("\">Configured repository with id '");
sb.append(repoId);
sb.append("'</r:repository>");
// Check if repo that should be re-indexed is listed in resource configuration (see property 'repository-id')
if(!allowed && repoId.equals(reindexRepo)) allowed = true;
}
}
// Check if repo that should be re-indexed is default repo
if(!allowed && "true".equals(defaultRepos) &&
("yanel_data".equals(reindexRepo) ||
"yanel_ac-policies".equals(reindexRepo) ||
"yanel_ac-identities".equals(reindexRepo) ||
"yanel_res-configs".equals(reindexRepo))) {
allowed = true;
}
// If it's an extra repo, allowed needs to be set to true
Repository repo = null;
if(allowed) {
try {
repo = getRealm().getRepository(reindexRepo);
} catch(Exception e) {
sb.append("<r:exception>Opening repo failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
}
// Perform re-indexing now
if(repo != null) {
YarepUtil yu = new YarepUtil();
String path = "/";
if (getEnvironment().getRequest().getParameter("path") != null) {
path = getEnvironment().getRequest().getParameter("path"); // INFO: Allows to re-index sub-tree, for example http://127.0.0.1:8080/yanel/yanel-website/re-index.html?repository=yanel_data&path=/en/documentation
}
try {
yu.indexRepository(repo, path);
sb.append("<r:message>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' was successful :-)</r:message>");
sb.append("<r:selected-repository id=\"" + reindexRepo + "\">" + repo.getName() + "</r:selected-repository>");
sb.append("<r:selected-path>" + path + "</r:selected-path>");
} catch(Exception e) {
sb.append("<r:exception>Re-indexing of repository '" + repo.getName() + "' starting at path '" + path + "' failed with exception: ");
sb.append(e.getMessage());
sb.append("</r:exception>");
}
} else if(reindexRepo != null) {
sb.append("<r:exception>Repository '" + reindexRepo + "' does either not exist or is not configured in order to be re-indexed.</r:exception>");
}
sb.append("</r:reindex>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
|
diff --git a/src/web/org/openmrs/web/controller/user/UserListController.java b/src/web/org/openmrs/web/controller/user/UserListController.java
index 0c1529da..4c77ee60 100644
--- a/src/web/org/openmrs/web/controller/user/UserListController.java
+++ b/src/web/org/openmrs/web/controller/user/UserListController.java
@@ -1,85 +1,85 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* 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.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.user;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.User;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
public class UserListController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Allows for Integers to be used as values in input tags. Normally, only strings and lists are
* expected
*
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
* org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
}
/**
* The onSubmit function receives the form/command object that was modified by the input form
* and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
return new ModelAndView(new RedirectView(getSuccessView()));
}
/**
* This is called prior to displaying a form for the first time. It tells Spring the
* form/command object to load into the request
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
- UserService us = Context.getUserService();
- userList = us.getAllUsers();
+ //UserService us = Context.getUserService();
+ //userList = us.getAllUsers();
}
return userList;
}
}
| true | true | protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
UserService us = Context.getUserService();
userList = us.getAllUsers();
}
return userList;
}
| protected Object formBackingObject(HttpServletRequest request) throws ServletException {
//default empty Object
List<User> userList = new Vector<User>();
//only fill the Object is the user has authenticated properly
if (Context.isAuthenticated()) {
//UserService us = Context.getUserService();
//userList = us.getAllUsers();
}
return userList;
}
|
diff --git a/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java b/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
index 2c5947379..53583df44 100644
--- a/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
+++ b/jsf/plugins/org.eclipse.jst.jsf.ui/src/org/eclipse/jst/jsf/ui/internal/validation/JSFValidator.java
@@ -1,197 +1,198 @@
/*******************************************************************************
* Copyright (c) 2001, 2008 Oracle 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:
* Oracle Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jst.jsf.ui.internal.validation;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jst.jsf.common.internal.JSPUtil;
import org.eclipse.jst.jsf.core.internal.JSFCorePlugin;
import org.eclipse.jst.jsf.core.jsfappconfig.JSFAppConfigUtils;
import org.eclipse.jst.jsf.validation.internal.IJSFViewValidator;
import org.eclipse.jst.jsf.validation.internal.JSFValidatorFactory;
import org.eclipse.jst.jsf.validation.internal.ValidationPreferences;
import org.eclipse.jst.jsp.core.internal.validation.JSPValidator;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
import org.eclipse.wst.validation.internal.provisional.core.IReporter;
import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
/**
* @author cbateman
*
*/
public class JSFValidator extends JSPValidator implements ISourceValidator
{
// TODO: should the source validator be a separate class in jsp.ui?
// problem with simple split off is that preference must also be split off
static final boolean DEBUG;
static
{
final String value = Platform
.getDebugOption("org.eclipse.jst.jsf.ui/validation"); //$NON-NLS-1$
DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$
}
private IDocument fDocument;
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#connect(org.eclipse.jface.text.IDocument)
*/
public void connect(final IDocument document)
{
fDocument = document;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#disconnect(org.eclipse.jface.text.IDocument)
*/
public void disconnect(final IDocument document)
{
// finished
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator#validate(org.eclipse.jface.text.IRegion,
* org.eclipse.wst.validation.internal.provisional.core.IValidationContext,
* org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
- if (fDocument instanceof IStructuredDocument)
+ if (fDocument instanceof IStructuredDocument
+ && file != null)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
private IFile getFile(final IValidationContext helper)
{
final String[] uris = helper.getURIs();
final IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
if (uris.length > 0)
{
return wsRoot.getFile(new Path(uris[0]));
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jst.jsp.core.internal.validation.JSPValidator#validateFile(org.eclipse.core.resources.IFile,
* org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
@Override
protected void validateFile(final IFile file, final IReporter reporter)
{
if (shouldValidate(file))
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(this,
reporter, file, prefs, model);
validator.validateView(file, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
private boolean shouldValidate(final IFile file)
{
return (JSPUtil.isJSPContentType(file)
&& JSFAppConfigUtils.isValidJSFProject(file.getProject()));
}
}
| true | true | public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
if (fDocument instanceof IStructuredDocument)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
| public void validate(final IRegion dirtyRegion,
final IValidationContext helper, final IReporter reporter)
{
if (DEBUG)
{
System.out.println("exec JSPSemanticsValidator.validateRegion"); //$NON-NLS-1$
}
final IFile file = getFile(helper);
if (fDocument instanceof IStructuredDocument
&& file != null)
{
final IStructuredDocument sDoc = (IStructuredDocument) fDocument;
final IStructuredDocumentRegion[] regions = sDoc
.getStructuredDocumentRegions(dirtyRegion.getOffset(),
dirtyRegion.getLength());
if (regions != null)
{
final IJSFViewValidator validator = JSFValidatorFactory
.createDefaultXMLValidator();
final ValidationPreferences prefs = new ValidationPreferences(
JSFCorePlugin.getDefault().getPreferenceStore());
prefs.load();
IStructuredModel model = null;
try
{
model = StructuredModelManager.getModelManager().getModelForRead(
file);
final ValidationReporter jsfReporter = new ValidationReporter(
this, reporter, file, prefs, model);
validator.validateView(file, regions, jsfReporter);
}
catch (final CoreException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
catch (final IOException e)
{
JSFCorePlugin.log("Error validating JSF", e); //$NON-NLS-1$
}
finally
{
if (null != model)
{
model.releaseFromRead();
}
}
}
}
}
|
diff --git a/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java b/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
index a8580de..14ad946 100644
--- a/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
+++ b/src/main/java/fi/vincit/jmobster/processor/languages/javascript/writer/JavaScriptWriter.java
@@ -1,324 +1,324 @@
package fi.vincit.jmobster.processor.languages.javascript.writer;/*
* Copyright 2012 Juha Siponen
*
* 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 fi.vincit.jmobster.processor.languages.BaseDataWriter;
import fi.vincit.jmobster.util.itemprocessor.ItemHandler;
import fi.vincit.jmobster.util.itemprocessor.ItemProcessor;
import fi.vincit.jmobster.util.itemprocessor.ItemStatus;
import fi.vincit.jmobster.util.writer.DataWriter;
/**
* Higher level abstraction for DataWriter that can write
* JavaScript to DataWriter. By default the writer checks that
* all functions and blocks are closed when the writer is closed.
* This feature can be turned of with {@link JavaScriptWriter#lenientModeOn}.
*/
@SuppressWarnings( "UnusedReturnValue" )
public class JavaScriptWriter extends BaseDataWriter<JavaScriptWriter> {
private static final String COMMENT_START = "/*";
private static final String COMMENT_LINE_START = " * ";
private static final String COMMENT_END = " */";
private static final String VARIABLE = "var";
private static final String BLOCK_START = "{";
private static final String BLOCK_END = "}";
private static final String ARRAY_START = "[";
private static final String ARRAY_END = "]";
private static final String ARRAY_SEPARATOR = ", ";
private static final String FUNCTION_ARG_START = "(";
private static final String FUNCTION_ARG_END = ")";
private static final String KEY_VALUE_SEPARATOR = ": ";
private static final String LIST_SEPARATOR = ",";
private static final String FUNCTION_DEF = "function";
private static final String STATEMENT_END = ";";
private static final String QUOTE = "\"";
private static final String ASSIGN = " = ";
private static final char KEYWORD_SEPARATOR = ' ';
private String space = " ";
private boolean lenientModeOn = false;
// Sanity checks.
private int functionsOpen = 0;
private int blocksOpen = 0;
private int functionCallsOpen = 0;
private boolean JSONmode = false;
private abstract static class ItemWriter<T> implements ItemHandler<T> {
private final JavaScriptWriter writer;
ItemWriter( JavaScriptWriter writer ) {
this.writer = writer;
}
JavaScriptWriter getWriter() {
return writer;
}
}
// TODO: Test that this works now as it should. Used to be as static variable which is VERY wrong
private final ItemWriter<Object> arrayWriter = new ItemWriter<Object>(this) {
@Override
public void process( Object item, ItemStatus status ) {
getWriter().write(item.toString(), ARRAY_SEPARATOR, !status.isLastItem());
}
};
public JavaScriptWriter(DataWriter writer) {
super(writer);
}
/**
* Start named function and starts a new block.
* @param name Function name
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startNamedFunction(String name, String... arguments) {
return write(FUNCTION_DEF + space).writeFunctionArgsAndStartBlock(name, arguments);
}
/**
* Start anonymous function and starts a new block.
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startAnonFunction(String... arguments) {
return write(FUNCTION_DEF).writeFunctionArgsAndStartBlock( "", arguments );
}
/**
* Writes function arguments and starts block
* @param arguments Function arguments
* @return Writer itself for chaining writes
*/
private JavaScriptWriter writeFunctionArgsAndStartBlock(String name, String... arguments) {
startFunctionCall(name);
ItemHandler<String> argumentProcessor = new ItemHandler<String>() {
@Override
public void process(String argument, ItemStatus status) {
write(argument, LIST_SEPARATOR + space, status.isNotLastItem());
}
};
ItemProcessor.process(argumentProcessor, arguments);
endFunctionCall().writeSpace();
return startBlock();
}
/**
* Ends function and blocks.
* @return Writer itself for chaining writes
* @param status Writes list separator item is last
*/
public JavaScriptWriter endFunction( ItemStatus status ) {
--functionsOpen;
return endBlock(status);
}
/**
* Stars a new block. Following lines will be indented.
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startBlock() {
++blocksOpen;
return writeLine( BLOCK_START ).indent();
}
/**
* Ends block. Indents back. Writes list separator (default ",") if isLast is false.
* @param status Writes list separator if item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter endBlock(ItemStatus status) {
--blocksOpen;
return indentBack().write( BLOCK_END ).writeLine("", LIST_SEPARATOR, status.isNotLastItem());
}
/**
* Start function call with block statement inside
* @param name Name of the function
* @return Writer itself for chaining writes
*/
public JavaScriptWriter startFunctionCallBlock(String name) {
return startFunctionCall(name).startBlock();
}
/**
* End function call with block statement
* @param status Writes list separator if item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter endFunctionCallBlock(ItemStatus status) {
--blocksOpen;
--functionCallsOpen;
return indentBack().write( BLOCK_END + ")" ).writeLine( "", LIST_SEPARATOR, status.isNotLastItem() );
}
public JavaScriptWriter endBlockStatement() {
write(BLOCK_END).endStatement();
return this;
}
/**
* Writes object key (also the separator, default ":")
* @param key Key name
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeKey(String key) {
return write("", QUOTE, JSONmode).write( key, QUOTE, JSONmode ).write( KEY_VALUE_SEPARATOR );
}
/**
* Writes object key and value. Writes list separator (default ",") if isLast is false.
* @param key Key name
* @param value Value
* @param status Writes list separator item is last
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeKeyValue(String key, String value, ItemStatus status) {
return writeKey(key).write(value).writeLine("", LIST_SEPARATOR, status.isNotLastItem());
}
/**
* Writes array of objects. Objects must have {@link Object#toString()} method
* implemented.
* @param status Writes list separator item is last
* @param objects Objects to write
* @return Writer itself for chaining writes
*/
public JavaScriptWriter writeArray(ItemStatus status, Object... objects) {
write(ARRAY_START);
ItemProcessor.process(arrayWriter, objects);
write(ARRAY_END);
write("", LIST_SEPARATOR, status.isNotLastItem());
writeLine("");
return this;
}
public JavaScriptWriter writeVariable(String name, String value) {
return writeVariable(name, value, VariableType.STRING);
}
public JavaScriptWriter endStatement() {
return writeLine(STATEMENT_END);
}
public static enum VariableType {
STRING, BLOCK, OTHER
}
public JavaScriptWriter writeVariable(String name, String value, VariableType type) {
final String quoteMark = type == VariableType.STRING ? QUOTE : "";
write(VARIABLE).write(KEYWORD_SEPARATOR).write(name).write(ASSIGN);
if( type != VariableType.BLOCK ) {
write(quoteMark).write(value).write(quoteMark).endStatement();
} else {
writeLine(BLOCK_START);
}
return this;
}
public JavaScriptWriter startFunctionCall(String functionName) {
++functionCallsOpen;
write(functionName).write(FUNCTION_ARG_START);
return this;
}
public JavaScriptWriter endFunctionCall() {
--functionCallsOpen;
write(FUNCTION_ARG_END);
return this;
}
public JavaScriptWriter writeComment(String comment) {
writeLine(COMMENT_START);
write(COMMENT_LINE_START);
writeLine(comment);
writeLine(COMMENT_END);
return this;
}
/**
* Writes space. Use this to enable easy to setup compact writing that
* can ignore spaces. To disable spaces use {@link JavaScriptWriter#setSpace(String)}
* method.
* @return Writer itself for chaining writes.
*/
public JavaScriptWriter writeSpace() {
write(space);
return this;
}
/**
* @throws IllegalStateException If lenient mode is on and the writer has unclosed functions or blocks.
*/
@Override
public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
- throw new IllegalStateException("There are still " + functionsOpen + "unclosed functions");
+ throw new IllegalStateException("There are still " + functionsOpen + " unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
- throw new IllegalStateException("There are still " + blocksOpen + "unclosed blocks");
+ throw new IllegalStateException("There are still " + blocksOpen + " unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
// Setters and getters
/**
* If set to false (default) {@link JavaScriptWriter#close()} will
* check that functions and blocks have been closed properly. If errors are found,
* exception will be thrown. If set to true, no checks are made and no exceptions
* are thrown.
* @param lenientModeOn Should the writer ignore obvious errors.
*/
public void setLenientMode( boolean lenientModeOn ) {
this.lenientModeOn = lenientModeOn;
}
/**
* Sets space sequence.
* @param space Space sequence
*/
public void setSpace(String space) {
this.space = space;
}
public void setJSONmode(boolean JSONmode) {
this.JSONmode = JSONmode;
}
}
| false | true | public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionsOpen + "unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
throw new IllegalStateException("There are still " + blocksOpen + "unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
| public void close() {
super.close();
if( !lenientModeOn ) {
if( functionsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionsOpen + " unclosed functions");
} else if( functionsOpen < 0 ) {
throw new IllegalStateException("Too many functions closed. " + Math.abs(functionsOpen) + " times too many.");
}
if( blocksOpen > 0 ) {
throw new IllegalStateException("There are still " + blocksOpen + " unclosed blocks");
} else if( blocksOpen < 0 ) {
throw new IllegalStateException("Too many blocks closed. " + Math.abs(blocksOpen) + " times too many.");
}
if( functionCallsOpen > 0 ) {
throw new IllegalStateException("There are still " + functionCallsOpen + " unclosed function calls");
} else if( functionCallsOpen < 0 ) {
throw new IllegalStateException("Too many function calls closed. " + Math.abs(functionCallsOpen) + " times too many.");
}
}
}
|
diff --git a/application/src/fi/local/social/network/activities/PeopleActivity.java b/application/src/fi/local/social/network/activities/PeopleActivity.java
index 7a3a115..902b115 100644
--- a/application/src/fi/local/social/network/activities/PeopleActivity.java
+++ b/application/src/fi/local/social/network/activities/PeopleActivity.java
@@ -1,75 +1,76 @@
package fi.local.social.network.activities;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import fi.local.social.network.R;
public class PeopleActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] mockup_values=new String[]{"Alex Yang","Tom Cruise","Tom Hanks","Jason Stathon","Joe Hu"};
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.people_item, R.id.label, mockup_values));
//ListView listView = getListView();
//listView.setTextFilterEnabled(true);
}
@Override
protected void onListItemClick(ListView l, View view, int position, long id) {
startActivity(new Intent(getApplicationContext(), ChatActivity.class));
//Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.layout.menu_people_nearby, menu);
return true;
}
//When a user clicks on an option menu item, a toast with the item title shows up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
- Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
+ //Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
+ startActivity(new Intent(getApplicationContext(), SettingActivity.class));
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
| public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle item selection
switch (item.getItemId()) {
case R.id.friends:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.event_list:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), EventsActivity.class));
return true;
case R.id.groups:
Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
case R.id.settings:
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), SettingActivity.class));
return true;
case R.id.new_event:
startActivity(new Intent(getApplicationContext(), NewEventActivity.class));
//Toast.makeText(getApplicationContext(),"You choose option menu item: "+item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
default:
break;
}
return false;
}
|
diff --git a/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java b/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
index fc1e3675..be28e8d0 100644
--- a/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
+++ b/src/main/src/org/compass/core/lucene/engine/LuceneSearchEngineInternalSearch.java
@@ -1,97 +1,97 @@
package org.compass.core.lucene.engine;
import java.io.IOException;
import java.util.List;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Searchable;
import org.apache.lucene.search.Searcher;
import org.compass.core.engine.SearchEngineException;
import org.compass.core.engine.SearchEngineInternalSearch;
import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager;
/**
* A Lucene specific search "internals", allowing for Lucene {@link IndexReader} and {@link Searcher}
* access.
*
* @author kimchy
*/
public class LuceneSearchEngineInternalSearch implements SearchEngineInternalSearch, LuceneDelegatedClose {
private MultiSearcher searcher;
protected MultiReader reader;
private boolean closed;
private List indexHolders;
/**
* Creates a new instance, with a searcher and index holders which will be used
* to release when calling close.
*
* @param searcher The searcher, which is also used to construct the reader
* @param indexHolders Holders to be released when calling close.
*/
public LuceneSearchEngineInternalSearch(MultiSearcher searcher, List indexHolders) {
this.searcher = searcher;
this.indexHolders = indexHolders;
}
/**
* Returns <code>true</code> if it represents an empty index scope.
*/
public boolean isEmpty() {
return searcher == null || searcher.getSearchables().length == 0;
}
/**
* Returns a Lucene {@link Searcher}.
*/
public Searcher getSearcher() {
return this.searcher;
}
/**
* Returns a Lucene {@link IndexReader}.
*/
public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
- throw new SearchEngineException("Failed to open readers for highlighting", e);
+ throw new SearchEngineException("Failed to open readers", e);
}
return this.reader;
}
/**
* Closes this instance of Lucene search "internals". This is an optional operation
* since Compass will take care of closing it when commit/rollback is called on the
* transaction.
*/
public void close() throws SearchEngineException {
if (closed) {
return;
}
closed = true;
if (indexHolders != null) {
for (int i = 0; i < indexHolders.size(); i++) {
LuceneSearchEngineIndexManager.LuceneIndexHolder indexHolder =
(LuceneSearchEngineIndexManager.LuceneIndexHolder) indexHolders.get(i);
indexHolder.release();
}
}
}
}
| true | true | public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
throw new SearchEngineException("Failed to open readers for highlighting", e);
}
return this.reader;
}
| public IndexReader getReader() throws SearchEngineException {
if (reader != null) {
return this.reader;
}
Searchable[] searchables = searcher.getSearchables();
IndexReader[] readers = new IndexReader[searchables.length];
for (int i = 0; i < searchables.length; i++) {
readers[i] = ((IndexSearcher) searchables[i]).getIndexReader();
}
try {
reader = new MultiReader(readers);
} catch (IOException e) {
throw new SearchEngineException("Failed to open readers", e);
}
return this.reader;
}
|
diff --git a/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java b/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
index 163097070..93616534e 100644
--- a/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
+++ b/forms/forms-server/src/main/java/org/bonitasoft/forms/server/accessor/api/ExpressionEvaluatorEngineClient.java
@@ -1,117 +1,118 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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.0 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.bonitasoft.forms.server.accessor.api;
import java.io.Serializable;
import java.util.Map;
import org.bonitasoft.console.common.server.utils.BPMExpressionEvaluationException;
import org.bonitasoft.engine.api.ProcessAPI;
import org.bonitasoft.engine.api.ProcessRuntimeAPI;
import org.bonitasoft.engine.expression.Expression;
import org.bonitasoft.engine.expression.ExpressionEvaluationException;
import org.bonitasoft.forms.server.accessor.widget.impl.XMLExpressionsUtil;
import org.bonitasoft.forms.server.api.impl.util.FormFieldValuesUtil;
/**
* @author Colin PUY
*
*/
public class ExpressionEvaluatorEngineClient {
private ProcessAPI processApi;
public ExpressionEvaluatorEngineClient(ProcessAPI processApi) {
this.processApi = processApi;
}
public Map<String, Serializable> evaluateExpressionsOnActivityInstance(long activityInstanceID,
Map<Expression, Map<String, Serializable>> expressionsWithContext) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnActivityInstance(activityInstanceID, expressionsWithContext);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on activity instance " + activityInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnProcessInstance(long processInstanceID, Map<Expression, Map<String, Serializable>> expressions)
throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnProcessInstance(processInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnProcessDefinition(long processDefinitionID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnProcessDefinition(processDefinitionID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on process definition " + processDefinitionID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnCompletedActivityInstance(long activityInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsOnCompletedActivityInstance(activityInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed activity instance " + activityInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsOnCompletedProcessInstance(long processInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionOnCompletedProcessInstance(processInstanceID, expressions);
} catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
public Map<String, Serializable> evaluateExpressionsAtProcessInstanciation(long processInstanceID,
Map<Expression, Map<String, Serializable>> expressions) throws BPMExpressionEvaluationException {
try {
return getProcessAPI().evaluateExpressionsAtProcessInstanciation(processInstanceID, expressions);
}catch (ExpressionEvaluationException e) {
throw new BPMExpressionEvaluationException("Error when evaluating expressions on completed process instance " + processInstanceID + ". " + buildEvaluationMessageLogDetail(e), e);
}
}
private ProcessRuntimeAPI getProcessAPI() {
return processApi;
}
private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
+ return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
}
- return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
+ return "Error on expression evaluation for the expression with name ["+ e.getExpressionName() +"].";
}
}
| false | true | private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
}
}
return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
| private String buildEvaluationMessageLogDetail(final ExpressionEvaluationException e) {
String[] splitExpressionName = null;
String expressionParentName = "unknown";
String expressionParentAttribute = "unknown";
if(e.getExpressionName()!=null){
splitExpressionName = e.getExpressionName().split(FormFieldValuesUtil.EXPRESSION_KEY_SEPARATOR);
if(splitExpressionName.length==2){
expressionParentName = splitExpressionName[0];
expressionParentAttribute = splitExpressionName[1];
return "Error on expression evaluation for the attribute ["+ expressionParentAttribute +"] of object ["+ expressionParentName +"].";
}
}
return "Error on expression evaluation for the expression with name ["+ e.getExpressionName() +"].";
}
|
diff --git a/src/com/android/calendar/EventInfoFragment.java b/src/com/android/calendar/EventInfoFragment.java
index c96789b7..25288951 100644
--- a/src/com/android/calendar/EventInfoFragment.java
+++ b/src/com/android/calendar/EventInfoFragment.java
@@ -1,1254 +1,1256 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.event.EditEventHelper;
import com.android.calendar.event.EventViewUtils;
import android.app.Activity;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.pim.EventRecurrence;
import android.provider.ContactsContract;
import android.provider.Calendar.Attendees;
import android.provider.Calendar.Calendars;
import android.provider.Calendar.Events;
import android.provider.Calendar.Reminders;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.Presence;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Linkify;
import android.text.util.Rfc822Token;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.QuickContactBadge;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Pattern;
public class EventInfoFragment extends Fragment implements View.OnClickListener,
AdapterView.OnItemSelectedListener {
public static final boolean DEBUG = true;
public static final String TAG = "EventInfoActivity";
private static final String BUNDLE_KEY_EVENT_ID = "key_event_id";
private static final String BUNDLE_KEY_START_MILLIS = "key_start_millis";
private static final String BUNDLE_KEY_END_MILLIS = "key_end_millis";
private static final int MAX_REMINDERS = 5;
/**
* These are the corresponding indices into the array of strings
* "R.array.change_response_labels" in the resource file.
*/
static final int UPDATE_SINGLE = 0;
static final int UPDATE_ALL = 1;
// Query tokens for QueryHandler
private static final int TOKEN_QUERY_EVENT = 0;
private static final int TOKEN_QUERY_CALENDARS = 1;
private static final int TOKEN_QUERY_ATTENDEES = 2;
private static final int TOKEN_QUERY_REMINDERS = 3;
private static final int TOKEN_QUERY_DUPLICATE_CALENDARS = 4;
private static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0 do not remove; used in DeleteEventHelper
Events.TITLE, // 1 do not remove; used in DeleteEventHelper
Events.RRULE, // 2 do not remove; used in DeleteEventHelper
Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper
Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper
Events.DTSTART, // 5 do not remove; used in DeleteEventHelper
Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper
Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper
Events.DESCRIPTION, // 8
Events.EVENT_LOCATION, // 9
Events.HAS_ALARM, // 10
Calendars.ACCESS_LEVEL, // 11
Calendars.COLOR, // 12
Events.HAS_ATTENDEE_DATA, // 13
Events.GUESTS_CAN_MODIFY, // 14
// TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider
Events.GUESTS_CAN_INVITE_OTHERS, // 15
Events.ORGANIZER, // 16
Events.ORIGINAL_EVENT // 17 do not remove; used in DeleteEventHelper
};
private static final int EVENT_INDEX_ID = 0;
private static final int EVENT_INDEX_TITLE = 1;
private static final int EVENT_INDEX_RRULE = 2;
private static final int EVENT_INDEX_ALL_DAY = 3;
private static final int EVENT_INDEX_CALENDAR_ID = 4;
private static final int EVENT_INDEX_SYNC_ID = 6;
private static final int EVENT_INDEX_EVENT_TIMEZONE = 7;
private static final int EVENT_INDEX_DESCRIPTION = 8;
private static final int EVENT_INDEX_EVENT_LOCATION = 9;
private static final int EVENT_INDEX_HAS_ALARM = 10;
private static final int EVENT_INDEX_ACCESS_LEVEL = 11;
private static final int EVENT_INDEX_COLOR = 12;
private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 13;
private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14;
private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15;
private static final int EVENT_INDEX_ORGANIZER = 16;
private static final String[] ATTENDEES_PROJECTION = new String[] {
Attendees._ID, // 0
Attendees.ATTENDEE_NAME, // 1
Attendees.ATTENDEE_EMAIL, // 2
Attendees.ATTENDEE_RELATIONSHIP, // 3
Attendees.ATTENDEE_STATUS, // 4
};
private static final int ATTENDEES_INDEX_ID = 0;
private static final int ATTENDEES_INDEX_NAME = 1;
private static final int ATTENDEES_INDEX_EMAIL = 2;
private static final int ATTENDEES_INDEX_RELATIONSHIP = 3;
private static final int ATTENDEES_INDEX_STATUS = 4;
private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=?";
private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
+ Attendees.ATTENDEE_EMAIL + " ASC";
static final String[] CALENDARS_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.DISPLAY_NAME, // 1
Calendars.OWNER_ACCOUNT, // 2
Calendars.ORGANIZER_CAN_RESPOND // 3
};
static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
static final int CALENDARS_INDEX_OWNER_CAN_RESPOND = 3;
static final String CALENDARS_WHERE = Calendars._ID + "=?";
static final String CALENDARS_DUPLICATE_NAME_WHERE = Calendars.DISPLAY_NAME + "=?";
private static final String[] REMINDERS_PROJECTION = new String[] {
Reminders._ID, // 0
Reminders.MINUTES, // 1
};
private static final int REMINDERS_INDEX_MINUTES = 1;
private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=? AND (" +
Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
Reminders.METHOD_DEFAULT + ")";
private static final String REMINDERS_SORT = Reminders.MINUTES;
private static final int MENU_GROUP_REMINDER = 1;
private static final int MENU_GROUP_EDIT = 2;
private static final int MENU_GROUP_DELETE = 3;
private static final int MENU_ADD_REMINDER = 1;
private static final int MENU_EDIT = 2;
private static final int MENU_DELETE = 3;
private static final int ATTENDEE_ID_NONE = -1;
private static final int ATTENDEE_NO_RESPONSE = -1;
private static final int[] ATTENDEE_VALUES = {
ATTENDEE_NO_RESPONSE,
Attendees.ATTENDEE_STATUS_ACCEPTED,
Attendees.ATTENDEE_STATUS_TENTATIVE,
Attendees.ATTENDEE_STATUS_DECLINED,
};
private View mView;
private LinearLayout mRemindersContainer;
private LinearLayout mOrganizerContainer;
private TextView mOrganizerView;
private Uri mUri;
private long mEventId;
private Cursor mEventCursor;
private Cursor mAttendeesCursor;
private Cursor mCalendarsCursor;
private long mStartMillis;
private long mEndMillis;
private boolean mHasAttendeeData;
private boolean mIsOrganizer;
private long mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
private boolean mOrganizerCanRespond;
private String mCalendarOwnerAccount;
private boolean mCanModifyCalendar;
private boolean mIsBusyFreeCalendar;
private boolean mCanModifyEvent;
private int mNumOfAttendees;
private String mOrganizer;
private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
private ArrayList<Integer> mReminderValues;
private ArrayList<String> mReminderLabels;
private int mDefaultReminderMinutes;
private boolean mOriginalHasAlarm;
private EditResponseHelper mEditResponseHelper;
private int mResponseOffset;
private int mOriginalAttendeeResponse;
private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
private boolean mIsRepeating;
private boolean mIsDuplicateName;
private Pattern mWildcardPattern = Pattern.compile("^.*$");
private LayoutInflater mLayoutInflater;
private LinearLayout mReminderAdder;
// TODO This can be removed when the contacts content provider doesn't return duplicates
private int mUpdateCounts;
private static class ViewHolder {
QuickContactBadge badge;
ImageView presence;
int updateCounts;
}
private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
private PresenceQueryHandler mPresenceQueryHandler;
private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0;
int PRESENCE_PROJECTION_PRESENCE_INDEX = 1;
int PRESENCE_PROJECTION_EMAIL_INDEX = 2;
int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3;
private static final String[] PRESENCE_PROJECTION = new String[] {
Email.CONTACT_ID, // 0
Email.CONTACT_PRESENCE, // 1
Email.DATA, // 2
Email.PHOTO_ID, // 3
};
ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>();
private int mColor;
private QueryHandler mHandler;
private class QueryHandler extends AsyncQueryService {
public QueryHandler(Context context) {
super(context);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// if the activity is finishing, then close the cursor and return
final Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
cursor.close();
return;
}
switch (token) {
case TOKEN_QUERY_EVENT:
mEventCursor = Utils.matrixCursorFromCursor(cursor);
if (initEventCursor()) {
// The cursor is empty. This can happen if the event was
// deleted.
// FRAG_TODO we should no longer rely on Activity.finish()
activity.finish();
return;
}
updateEvent(mView);
// start calendar query
Uri uri = Calendars.CONTENT_URI;
String[] args = new String[] {
Long.toString(mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID))};
startQuery(TOKEN_QUERY_CALENDARS, null, uri, CALENDARS_PROJECTION,
CALENDARS_WHERE, args, null);
break;
case TOKEN_QUERY_CALENDARS:
mCalendarsCursor = Utils.matrixCursorFromCursor(cursor);
updateCalendar(mView);
// FRAG_TODO fragments shouldn't set the title anymore
updateTitle();
// update the action bar since our option set might have changed
activity.invalidateOptionsMenu();
// this is used for both attendees and reminders
args = new String[] { Long.toString(mEventId) };
// start attendees query
uri = Attendees.CONTENT_URI;
startQuery(TOKEN_QUERY_ATTENDEES, null, uri, ATTENDEES_PROJECTION,
ATTENDEES_WHERE, args, ATTENDEES_SORT_ORDER);
// start reminders query
mOriginalHasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
if (mOriginalHasAlarm) {
uri = Reminders.CONTENT_URI;
startQuery(TOKEN_QUERY_REMINDERS, null, uri, REMINDERS_PROJECTION,
REMINDERS_WHERE, args, REMINDERS_SORT);
} else {
// if no reminders, hide the appropriate fields
updateRemindersVisibility();
}
break;
case TOKEN_QUERY_ATTENDEES:
mAttendeesCursor = Utils.matrixCursorFromCursor(cursor);
initAttendeesCursor(mView);
updateResponse(mView);
break;
case TOKEN_QUERY_REMINDERS:
MatrixCursor reminderCursor = Utils.matrixCursorFromCursor(cursor);
try {
// First pass: collect all the custom reminder minutes
// (e.g., a reminder of 8 minutes) into a global list.
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
EventViewUtils.addMinutesToList(
activity, mReminderValues, mReminderLabels, minutes);
}
// Second pass: create the reminder spinners
reminderCursor.moveToPosition(-1);
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
mOriginalMinutes.add(minutes);
EventViewUtils.addReminder(activity, mRemindersContainer,
EventInfoFragment.this, mReminderItems, mReminderValues,
mReminderLabels, minutes);
}
} finally {
updateRemindersVisibility();
reminderCursor.close();
}
break;
case TOKEN_QUERY_DUPLICATE_CALENDARS:
mIsDuplicateName = cursor.getCount() > 1;
String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
Resources res = activity.getResources();
TextView ownerText = (TextView) mView.findViewById(R.id.owner);
ownerText.setText(ownerAccount);
ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color));
} else {
setVisibilityCommon(mView, R.id.owner, View.GONE);
}
setTextCommon(mView, R.id.calendar, calendarName);
break;
}
cursor.close();
}
}
public EventInfoFragment() {
mUri = null;
}
public EventInfoFragment(Uri uri, long startMillis, long endMillis, int attendeeResponse) {
mUri = uri;
mStartMillis = startMillis;
mEndMillis = endMillis;
mAttendeeResponseFromIntent = attendeeResponse;
}
public EventInfoFragment(long eventId, long startMillis, long endMillis) {
this(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
startMillis, endMillis, EventInfoActivity.ATTENDEE_NO_RESPONSE);
mEventId = eventId;
}
// This is called when one of the "remove reminder" buttons is selected.
public void onClick(View v) {
LinearLayout reminderItem = (LinearLayout) v.getParent();
LinearLayout parent = (LinearLayout) reminderItem.getParent();
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility();
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// If they selected the "No response" option, then don't display the
// dialog asking which events to change.
if (id == 0 && mResponseOffset == 0) {
return;
}
// If this is not a repeating event, then don't display the dialog
// asking which events to change.
if (!mIsRepeating) {
return;
}
// If the selection is the same as the original, then don't display the
// dialog asking which events to change.
int index = findResponseIndexFor(mOriginalAttendeeResponse);
if (position == index + mResponseOffset) {
return;
}
// This is a repeating event. We need to ask the user if they mean to
// change just this one instance or all instances.
mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
}
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mEditResponseHelper = new EditResponseHelper(activity);
setHasOptionsMenu(true);
mHandler = new QueryHandler(activity);
mPresenceQueryHandler = new PresenceQueryHandler(activity, activity.getContentResolver());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mLayoutInflater = inflater;
mView = inflater.inflate(R.layout.event_info_activity, null);
mRemindersContainer = (LinearLayout) mView.findViewById(R.id.reminders_container);
mOrganizerContainer = (LinearLayout) mView.findViewById(R.id.organizer_container);
mOrganizerView = (TextView) mView.findViewById(R.id.organizer);
// Initialize the reminder values array.
Resources r = getActivity().getResources();
String[] strings = r.getStringArray(R.array.reminder_minutes_values);
int size = strings.length;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for (int i = 0 ; i < size ; i++) {
list.add(Integer.parseInt(strings[i]));
}
mReminderValues = list;
String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(getActivity());
String durationString =
prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
mDefaultReminderMinutes = Integer.parseInt(durationString);
// Setup the + Add Reminder Button
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
addReminder();
}
};
ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add);
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mReminderAdder = (LinearLayout) mView.findViewById(R.id.reminder_adder);
if (mUri == null) {
// restore event ID from bundle
mEventId = savedInstanceState.getLong(BUNDLE_KEY_EVENT_ID);
mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
mStartMillis = savedInstanceState.getLong(BUNDLE_KEY_START_MILLIS);
mEndMillis = savedInstanceState.getLong(BUNDLE_KEY_END_MILLIS);
}
// start loading the data
mHandler.startQuery(TOKEN_QUERY_EVENT, null, mUri, EVENT_PROJECTION,
null, null, null);
return mView;
}
private void updateTitle() {
Resources res = getActivity().getResources();
if (mCanModifyCalendar && !mIsOrganizer) {
getActivity().setTitle(res.getString(R.string.event_info_title_invite));
} else {
getActivity().setTitle(res.getString(R.string.event_info_title));
}
}
/**
* Initializes the event cursor, which is expected to point to the first
* (and only) result from a query.
* @return true if the cursor is empty.
*/
private boolean initEventCursor() {
if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
return true;
}
mEventCursor.moveToFirst();
mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
mIsRepeating = (rRule != null);
return false;
}
private static class Attendee {
String mName;
String mEmail;
Attendee(String name, String email) {
mName = name;
mEmail = email;
}
}
@SuppressWarnings("fallthrough")
private void initAttendeesCursor(View view) {
mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
mNumOfAttendees = 0;
if (mAttendeesCursor != null) {
mNumOfAttendees = mAttendeesCursor.getCount();
if (mAttendeesCursor.moveToFirst()) {
mAcceptedAttendees.clear();
mDeclinedAttendees.clear();
mTentativeAttendees.clear();
mNoResponseAttendees.clear();
do {
int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
Attendees.RELATIONSHIP_ORGANIZER) {
// Overwrites the one from Event table if available
if (name != null && name.length() > 0) {
mOrganizer = name;
} else if (email != null && email.length() > 0) {
mOrganizer = email;
}
}
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
mCalendarOwnerAccount.equalsIgnoreCase(email)) {
mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
} else {
// Don't show your own status in the list because:
// 1) it doesn't make sense for event without other guests.
// 2) there's a spinner for that for events with guests.
switch(status) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
mAcceptedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
mDeclinedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_NONE:
mNoResponseAttendees.add(new Attendee(name, email));
// Fallthrough so that no response is a subset of tentative
default:
mTentativeAttendees.add(new Attendee(name, email));
}
}
} while (mAttendeesCursor.moveToNext());
mAttendeesCursor.moveToFirst();
updateAttendees(view);
}
}
// only show the organizer if we're not the organizer and if
// we have attendee data (might have been removed by the server
// for events with a lot of attendees).
if (!mIsOrganizer && mHasAttendeeData) {
mOrganizerContainer.setVisibility(View.VISIBLE);
mOrganizerView.setText(mOrganizer);
} else {
mOrganizerContainer.setVisibility(View.GONE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_EVENT_ID, mEventId);
outState.putLong(BUNDLE_KEY_START_MILLIS, mStartMillis);
outState.putLong(BUNDLE_KEY_END_MILLIS, mEndMillis);
}
@Override
public void onDestroyView() {
ArrayList<Integer> reminderMinutes = EventViewUtils.reminderItemsToMinutes(mReminderItems,
mReminderValues);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
boolean changed = EditEventHelper.saveReminders(ops, mEventId, reminderMinutes,
mOriginalMinutes, false /* no force save */);
mHandler.startBatch(mHandler.getNextToken(), null,
Calendars.CONTENT_URI.getAuthority(), ops, Utils.UNDO_DELAY);
// Update the "hasAlarm" field for the event
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
int len = reminderMinutes.size();
boolean hasAlarm = len > 0;
if (hasAlarm != mOriginalHasAlarm) {
ContentValues values = new ContentValues();
values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
mHandler.startUpdate(mHandler.getNextToken(), null, uri, values,
null, null, Utils.UNDO_DELAY);
}
changed |= saveResponse();
if (changed) {
Toast.makeText(getActivity(), R.string.saving_event, Toast.LENGTH_SHORT).show();
}
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mEventCursor != null) {
mEventCursor.close();
}
if (mCalendarsCursor != null) {
mCalendarsCursor.close();
}
if (mAttendeesCursor != null) {
mAttendeesCursor.close();
}
}
private boolean canAddReminders() {
return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
}
private void addReminder() {
// TODO: when adding a new reminder, make it different from the
// last one in the list (if any).
if (mDefaultReminderMinutes == 0) {
EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems,
mReminderValues, mReminderLabels, 10 /* minutes */);
} else {
EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems,
mReminderValues, mReminderLabels, mDefaultReminderMinutes);
}
updateRemindersVisibility();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item;
item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
R.string.add_new_reminder);
item.setIcon(R.drawable.ic_menu_reminder);
item.setAlphabeticShortcut('r');
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
item.setIcon(android.R.drawable.ic_menu_edit);
item.setAlphabeticShortcut('e');
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
item.setIcon(android.R.drawable.ic_menu_delete);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean canAddReminders = canAddReminders();
menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD_REMINDER:
addReminder();
break;
case MENU_EDIT:
doEdit();
break;
case MENU_DELETE:
doDelete();
break;
}
return true;
}
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (keyCode == KeyEvent.KEYCODE_DEL) {
// doDelete();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
private void updateRemindersVisibility() {
if (mIsBusyFreeCalendar) {
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersContainer.setVisibility(View.VISIBLE);
mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
}
}
/**
* Asynchronously saves the response to an invitation if the user changed
* the response. Returns true if the database will be updated.
*
* @param cr the ContentResolver
* @return true if the database will be changed
*/
private boolean saveResponse() {
if (mAttendeesCursor == null || mEventCursor == null) {
return false;
}
Spinner spinner = (Spinner) getView().findViewById(R.id.response_value);
int position = spinner.getSelectedItemPosition() - mResponseOffset;
if (position <= 0) {
return false;
}
int status = ATTENDEE_VALUES[position];
// If the status has not changed, then don't update the database
if (status == mOriginalAttendeeResponse) {
return false;
}
// If we never got an owner attendee id we can't set the status
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
return false;
}
if (!mIsRepeating) {
// This is a non-repeating event
updateResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
}
// This is a repeating event
int whichEvents = mEditResponseHelper.getWhichEvents();
switch (whichEvents) {
case -1:
return false;
case UPDATE_SINGLE:
createExceptionResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
case UPDATE_ALL:
updateResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
default:
Log.e(TAG, "Unexpected choice for updating invitation response");
break;
}
return false;
}
private void updateResponse(long eventId, long attendeeId, int status) {
// Update the attendee status in the attendees table. the provider
// takes care of updating the self attendance status.
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
}
values.put(Attendees.ATTENDEE_STATUS, status);
values.put(Attendees.EVENT_ID, eventId);
Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
mHandler.startUpdate(mHandler.getNextToken(), null, uri, values,
null, null, Utils.UNDO_DELAY);
}
private void createExceptionResponse(long eventId, long attendeeId,
int status) {
if (mEventCursor == null || !mEventCursor.moveToFirst()) {
return;
}
ContentValues values = new ContentValues();
String title = mEventCursor.getString(EVENT_INDEX_TITLE);
String timezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
int calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String syncId = mEventCursor.getString(EVENT_INDEX_SYNC_ID);
values.put(Events.TITLE, title);
values.put(Events.EVENT_TIMEZONE, timezone);
values.put(Events.ALL_DAY, allDay ? 1 : 0);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.DTSTART, mStartMillis);
values.put(Events.DTEND, mEndMillis);
values.put(Events.ORIGINAL_EVENT, syncId);
values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
values.put(Events.SELF_ATTENDEE_STATUS, status);
// Create a recurrence exception
mHandler.startInsert(mHandler.getNextToken(), null,
Events.CONTENT_URI, values, Utils.UNDO_DELAY);
}
private int findResponseIndexFor(int response) {
int size = ATTENDEE_VALUES.length;
for (int index = 0; index < size; index++) {
if (ATTENDEE_VALUES[index] == response) {
return index;
}
}
return 0;
}
private void doEdit() {
CalendarController.getInstance(getActivity()).sendEventRelatedEvent(
this, EventType.EDIT_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0);
}
private void doDelete() {
CalendarController.getInstance(getActivity()).sendEventRelatedEvent(
this, EventType.DELETE_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0);
}
private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
+ setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
+ setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
private void updateCalendar(View view) {
mCalendarOwnerAccount = "";
if (mCalendarsCursor != null && mEventCursor != null) {
mCalendarsCursor.moveToFirst();
String tempAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
mCalendarOwnerAccount = (tempAccount == null) ? "" : tempAccount;
mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0;
String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
// start duplicate calendars query
mHandler.startQuery(TOKEN_QUERY_DUPLICATE_CALENDARS, null, Calendars.CONTENT_URI,
CALENDARS_PROJECTION, CALENDARS_DUPLICATE_NAME_WHERE,
new String[] {displayName}, null);
String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
mOrganizer = eventOrganizer;
mCanModifyCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
mIsBusyFreeCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
mCanModifyEvent = mCanModifyCalendar
&& (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
} else {
setVisibilityCommon(view, R.id.calendar_container, View.GONE);
}
}
private void updateAttendees(View view) {
LinearLayout attendeesLayout = (LinearLayout) view.findViewById(R.id.attendee_list);
attendeesLayout.removeAllViewsInLayout();
++mUpdateCounts;
if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 &&
mTentativeAttendees.size() == mNoResponseAttendees.size()) {
// If all guests have no response just list them as guests,
CharSequence guestsLabel =
getActivity().getResources().getText(R.string.attendees_label);
addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel);
} else {
// If we have any responses then divide them up by response
CharSequence[] entries;
entries = getActivity().getResources().getTextArray(R.array.response_labels2);
addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
}
}
private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
CharSequence sectionTitle) {
if (attendees.size() == 0) {
return;
}
// Yes/No/Maybe Title
View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
titleView.findViewById(R.id.badge).setVisibility(View.GONE);
View divider = titleView.findViewById(R.id.separator);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
TextView title = (TextView) titleView.findViewById(R.id.name);
title.setText(getActivity().getString(R.string.response_label, sectionTitle,
attendees.size()));
title.setTextAppearance(getActivity(), R.style.TextAppearance_EventInfo_Label);
attendeeList.addView(titleView);
// Attendees
int numOfAttendees = attendees.size();
StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
String[] selectionArgs = new String[numOfAttendees];
for (int i = 0; i < numOfAttendees; ++i) {
Attendee attendee = attendees.get(i);
selectionArgs[i] = attendee.mEmail;
View v = mLayoutInflater.inflate(R.layout.contact_item, null);
v.setTag(attendee);
View separator = v.findViewById(R.id.separator);
separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// Text
TextView tv = (TextView) v.findViewById(R.id.name);
String name = attendee.mName;
if (name == null || name.length() == 0) {
name = attendee.mEmail;
}
tv.setText(name);
ViewHolder vh = new ViewHolder();
vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
vh.badge.assignContactFromEmail(attendee.mEmail, true);
vh.presence = (ImageView) v.findViewById(R.id.presence);
mViewHolders.put(attendee.mEmail, vh);
if (i == 0) {
selection.append('?');
} else {
selection.append(", ?");
}
attendeeList.addView(v);
}
selection.append(')');
mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
}
private class PresenceQueryHandler extends AsyncQueryHandler {
Context mContext;
public PresenceQueryHandler(Context context, ContentResolver cr) {
super(cr);
mContext = context;
}
@Override
protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
if (cursor == null) {
if (DEBUG) {
Log.e(TAG, "onQueryComplete: cursor == null");
}
return;
}
try {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
ViewHolder vh = mViewHolders.get(email);
int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
if (DEBUG) {
Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
+ " Email: " + email);
}
if (vh == null) {
continue;
}
ImageView presenceView = vh.presence;
if (presenceView != null) {
int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
presenceView.setVisibility(View.VISIBLE);
}
if (photoId > 0 && vh.updateCounts < queryIndex) {
vh.updateCounts = queryIndex;
Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
// TODO, modify to batch queries together
ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
vh.badge, personUri, R.drawable.ic_contact_picture);
}
}
} finally {
cursor.close();
}
}
}
void updateResponse(View view) {
// we only let the user accept/reject/etc. a meeting if:
// a) you can edit the event's containing calendar AND
// b) you're not the organizer and only attendee AND
// c) organizerCanRespond is enabled for the calendar
// (if the attendee data has been hidden, the visible number of attendees
// will be 1 -- the calendar owner's).
// (there are more cases involved to be 100% accurate, such as
// paying attention to whether or not an attendee status was
// included in the feed, but we're currently omitting those corner cases
// for simplicity).
if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) ||
(mIsOrganizer && !mOrganizerCanRespond)) {
setVisibilityCommon(view, R.id.response_container, View.GONE);
return;
}
setVisibilityCommon(view, R.id.response_container, View.VISIBLE);
Spinner spinner = (Spinner) view.findViewById(R.id.response_value);
mResponseOffset = 0;
/* If the user has previously responded to this event
* we should not allow them to select no response again.
* Switch the entries to a set of entries without the
* no response option.
*/
if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
&& (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
&& (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
CharSequence[] entries;
entries = getActivity().getResources().getTextArray(R.array.response_labels2);
mResponseOffset = -1;
ArrayAdapter<CharSequence> adapter =
new ArrayAdapter<CharSequence>(getActivity(),
android.R.layout.simple_spinner_item, entries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
int index;
if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
index = findResponseIndexFor(mAttendeeResponseFromIntent);
} else {
index = findResponseIndexFor(mOriginalAttendeeResponse);
}
spinner.setSelection(index + mResponseOffset);
spinner.setOnItemSelectedListener(this);
}
private void setTextCommon(View view, int id, CharSequence text) {
TextView textView = (TextView) view.findViewById(id);
if (textView == null)
return;
textView.setText(text);
}
private void setVisibilityCommon(View view, int id, int visibility) {
View v = view.findViewById(id);
if (v != null) {
v.setVisibility(visibility);
}
return;
}
/**
* Taken from com.google.android.gm.HtmlConversationActivity
*
* Send the intent that shows the Contact info corresponding to the email address.
*/
public void showContactInfo(Attendee attendee, Rect rect) {
// First perform lookup query to find existing contact
final ContentResolver resolver = getActivity().getContentResolver();
final String address = attendee.mEmail;
final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
Uri.encode(address));
final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
if (lookupUri != null) {
// Found matching contact, trigger QuickContact
QuickContact.showQuickContact(getActivity(), rect, lookupUri,
QuickContact.MODE_MEDIUM, null);
} else {
// No matching contact, ask user to create one
final Uri mailUri = Uri.fromParts("mailto", address, null);
final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
// Pass along full E-mail string for possible create dialog
Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
// Only provide personal name hint if we have one
final String senderPersonal = attendee.mName;
if (!TextUtils.isEmpty(senderPersonal)) {
intent.putExtra(Intents.Insert.NAME, senderPersonal);
}
startActivity(intent);
}
}
}
| false | true | private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
| private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
|
diff --git a/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java b/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
index 6796d41..a13f2fb 100644
--- a/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
+++ b/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
@@ -1,55 +1,55 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.alarmclock;
import com.android.deskclock.AlarmClock;
import com.android.deskclock.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
/**
* Simple widget to show analog clock.
*/
public class AnalogDefaultAppWidgetProvider extends BroadcastReceiver {
static final String TAG = "AnalogDefaultAppWidgetProvider";
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
- R.layout.analogdefault_appwidget);
+ R.layout.analogsecond_appwidget);
- views.setOnClickPendingIntent(R.id.analogdefault_appwidget,
+ views.setOnClickPendingIntent(R.id.analogsecond_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
}
| false | true | public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.analogdefault_appwidget);
views.setOnClickPendingIntent(R.id.analogdefault_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
| public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.analogsecond_appwidget);
views.setOnClickPendingIntent(R.id.analogsecond_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
|
diff --git a/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java b/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
index 4c2abff..fc5937b 100644
--- a/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
+++ b/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
@@ -1,113 +1,113 @@
/*
* Copyright 2010 Jasha Joachimsthal
*
* 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.onehippo.forge.weblogdemo.components;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.hippoecm.hst.content.beans.query.HstQuery;
import org.hippoecm.hst.content.beans.query.HstQueryResult;
import org.hippoecm.hst.content.beans.query.exceptions.QueryException;
import org.hippoecm.hst.content.beans.query.filter.Filter;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.content.beans.standard.HippoBeanIterator;
import org.hippoecm.hst.core.component.HstComponentException;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.onehippo.forge.weblogdemo.beans.BaseDocument;
/**
* Simple search component. Excludes construction
* @author Jasha Joachimsthal
*
*/
public class Search extends BaseSiteComponent {
private static final String SEARCHFOR_PARAM = "searchfor";
private static final String PAGEPARAM = "page";
public static final Logger log = LoggerFactory.getLogger(Search.class);
public static final int PAGESIZE = 10;
@Override
public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
- long pages = beansSize / PAGESIZE;
+ long pages = beansSize % PAGESIZE > 0L ? beansSize / PAGESIZE + 1L : beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
}
| true | true | public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
long pages = beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
| public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
long pages = beansSize % PAGESIZE > 0L ? beansSize / PAGESIZE + 1L : beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
|
diff --git a/n3phele/src/n3phele/service/actions/StackServiceAction.java b/n3phele/src/n3phele/service/actions/StackServiceAction.java
index b586445..8c03d2a 100644
--- a/n3phele/src/n3phele/service/actions/StackServiceAction.java
+++ b/n3phele/src/n3phele/service/actions/StackServiceAction.java
@@ -1,266 +1,266 @@
package n3phele.service.actions;
import java.io.FileNotFoundException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.json.JSONArray;
import org.json.JSONException;
import n3phele.service.core.NotFoundException;
import n3phele.service.core.ResourceFile;
import n3phele.service.core.ResourceFileFactory;
import n3phele.service.model.Action;
import n3phele.service.model.CloudProcess;
import n3phele.service.model.Context;
import n3phele.service.model.Relationship;
import n3phele.service.model.SignalKind;
import n3phele.service.model.Stack;
import n3phele.service.model.core.User;
import n3phele.service.rest.impl.ActionResource;
import n3phele.service.rest.impl.CloudProcessResource;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.EntitySubclass;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Unindex;
@EntitySubclass(index = true)
@XmlRootElement(name = "StackServiceAction")
@XmlType(name = "StackServiceAction", propOrder = { "serviceDescription", "stacks", "relationships" })
@Unindex
@Cache
public class StackServiceAction extends ServiceAction {
// generates the id of stacks
private long stackNumber;
private String serviceDescription;
private List<String> adopted = new ArrayList<String>();
@Embed private List<Stack> stacks = new ArrayList<Stack>();
@Embed private List<Relationship> relationships = new ArrayList<Relationship>();
@Ignore private ResourceFileFactory resourceFileFactory;
public StackServiceAction()
{
super();
stackNumber = 0;
this.resourceFileFactory = new ResourceFileFactory();
}
public StackServiceAction(String description, String name, User owner, Context context) {
super(owner, name, context);
this.serviceDescription = description;
stackNumber = 0;
}
@Override
public Action create(URI owner, String name, Context context) {
super.create(owner, name, context);
this.serviceDescription = "";
registerServiceCommandsToContext();
return this;
}
public void setResourceFileFactory(ResourceFileFactory factory)
{
this.resourceFileFactory = factory;
}
public void registerServiceCommandsToContext()
{
List<String> commands = new ArrayList<String>();
try {
ResourceFile fileConfiguration = this.resourceFileFactory.create("n3phele.resource.service_commands");
String commandsString = fileConfiguration.get("charms", "");
JSONArray jsonArray = new JSONArray(commandsString);
for(int i=0; i<jsonArray.length(); i++)
{
commands.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
this.context.putValue("deploy_commands", commands);
}
public List<String> getAcceptedCommands()
{
List<String> commands = this.context.getListValue("deploy_commands");
if(commands == null) commands = new ArrayList<String>();
return commands;
}
public void addNewCommand(String newCommandUri)
{
List<String> oldCommands = this.context.getListValue("deploy_commands");
List<String> commands = new ArrayList<String>(oldCommands);
commands.add(newCommandUri);
this.context.putValue("deploy_commands", commands);
}
/*
* Automatic Generated Methods
*/
@Override
public String getDescription() {
return "StackService " + this.getName();
}
public String getServiceDescription() {
return this.serviceDescription;
}
public void setServiceDescription(String description) {
this.serviceDescription = description;
}
public List<Stack> getStacks() {
return this.stacks;
}
public void setStacks(List<Stack> stacks) {
this.stacks = stacks;
}
public boolean addStack(Stack stack) {
if(stack.getId() == -1)
stack.setId(this.getNextStackNumber());
return stacks.add(stack);
}
public List<Relationship> getRelationships() {
return this.relationships;
}
public void setRelationships(List<Relationship> relationships) {
this.relationships = relationships;
}
public boolean addRelationhip(Relationship relation) {
return relationships.add(relation);
}
public long getNextStackNumber() {
long id = stackNumber;
stackNumber++;
return id;
}
@Override
public void cancel() {
log.info("Cancelling " + stacks.size() + " stacks");
for (Stack stack : stacks) {
for (URI uri : stack.getVms()) {
try {
processLifecycle().cancel(uri);
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
for (String vm : adopted) {
try {
processLifecycle().cancel(URI.create(vm));
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
@Override
public void dump() {
log.info("Dumping " + stacks.size() + " stacks");
for (Stack stack : stacks) {
for (URI uri : stack.getVms()) {
try {
processLifecycle().dump(uri);
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
for (String vm : adopted) {
try {
processLifecycle().cancel(URI.create(vm));
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
@Override
public String toString() {
return "StackServiceAction [description=" + this.serviceDescription + ", stacks=" + this.stacks + ", relationships=" + this.relationships + ", idStack=" + this.stackNumber + ", context=" + this.context + ", name=" + this.name + ", uri=" + this.uri + ", owner=" + this.owner + ", isPublic="
+ this.isPublic + "]";
}
@Override
public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
- if (action instanceof AssimilateAction) {
+ if (action instanceof AssimilateVMAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
}
| true | true | public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
if (action instanceof AssimilateAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
| public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
if (action instanceof AssimilateVMAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
|
diff --git a/org/xbill/DNS/Address.java b/org/xbill/DNS/Address.java
index de7e4b3..3e0a74f 100644
--- a/org/xbill/DNS/Address.java
+++ b/org/xbill/DNS/Address.java
@@ -1,153 +1,156 @@
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.net.*;
/**
* Routines dealing with IP addresses. Includes functions similar to
* those in the java.net.InetAddress class.
*
* @author Brian Wellington
*/
public final class Address {
private
Address() {}
/**
* Convert a string containing an IP address to an array of 4 integers.
* @param s The string
* @return The address
*/
public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
+ /* Octets shouldn't start with 0, unless they are 0. */
+ if (numDigits > 0 && values[currentOctet] == 0)
+ return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
/**
* Determines if a string contains a valid IP address.
* @param s The string
* @return Whether the string contains a valid IP address
*/
public static boolean
isDottedQuad(String s) {
int [] address = Address.toArray(s);
return (address != null);
}
/**
* Converts a byte array containing an IPv4 address into a dotted quad string.
* @param addr The byte array
* @return The string representation
*/
public static String
toDottedQuad(byte [] addr) {
return ((addr[0] & 0xFF) + "." + (addr[1] & 0xFF) + "." +
(addr[2] & 0xFF) + "." + (addr[3] & 0xFF));
}
private static Record []
lookupHostName(String name) throws UnknownHostException {
try {
Record [] records = new Lookup(name).run();
if (records == null)
throw new UnknownHostException("unknown host");
return records;
}
catch (TextParseException e) {
throw new UnknownHostException("invalid name");
}
}
/**
* Determines the IP address of a host
* @param name The hostname to look up
* @return The first matching IP address
* @exception UnknownHostException The hostname does not have any addresses
*/
public static InetAddress
getByName(String name) throws UnknownHostException {
if (isDottedQuad(name))
return InetAddress.getByName(name);
Record [] records = lookupHostName(name);
ARecord a = (ARecord) records[0];
return a.getAddress();
}
/**
* Determines all IP address of a host
* @param name The hostname to look up
* @return All matching IP addresses
* @exception UnknownHostException The hostname does not have any addresses
*/
public static InetAddress []
getAllByName(String name) throws UnknownHostException {
if (isDottedQuad(name))
return InetAddress.getAllByName(name);
Record [] records = lookupHostName(name);
InetAddress [] addrs = new InetAddress[records.length];
for (int i = 0; i < records.length; i++) {
ARecord a = (ARecord) records[i];
addrs[i] = a.getAddress();
}
return addrs;
}
/**
* Determines the hostname for an address
* @param addr The address to look up
* @return The associated host name
* @exception UnknownHostException There is no hostname for the address
*/
public static String
getHostName(InetAddress addr) throws UnknownHostException {
Name name = ReverseMap.fromAddress(addr);
Record [] records = new Lookup(name, Type.PTR).run();
if (records == null)
throw new UnknownHostException("unknown address");
PTRRecord ptr = (PTRRecord) records[0];
return ptr.getTarget().toString();
}
}
| true | true | public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
| public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
/* Octets shouldn't start with 0, unless they are 0. */
if (numDigits > 0 && values[currentOctet] == 0)
return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
|
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
index e3933e38f..54cf6dc7b 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
@@ -1,111 +1,111 @@
package com.badlogic.gdx.tests;
import java.util.Arrays;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.loaders.obj.ObjLoader;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.tests.utils.GdxTest;
public class EdgeDetectionTest extends GdxTest {
@Override public boolean needsGL20 () {
return true;
}
FPSLogger logger;
ShaderProgram shader;
Mesh mesh;
FrameBuffer fbo;
PerspectiveCamera cam;
Matrix4 matrix = new Matrix4();
float angle = 0;
TextureRegion fboRegion;
SpriteBatch batch;
ShaderProgram batchShader;
float[] filter = { 0, 0.25f, 0,
0.25f, -1, 0.25f,
0, 0.25f, 0,
};
float[] offsets = new float[18];
public void create() {
ShaderProgram.pedantic = false;
shader = new ShaderProgram(Gdx.files.internal("data/default.vert").readString(),
Gdx.files.internal("data/depthtocolor.frag").readString());
if(!shader.isCompiled()) {
Gdx.app.log("EdgeDetectionTest", "couldn't compile scene shader: " + shader.getLog());
}
batchShader = new ShaderProgram(Gdx.files.internal("data/batch.vert").readString(),
Gdx.files.internal("data/convolution.frag").readString());
if(!batchShader.isCompiled()) {
Gdx.app.log("EdgeDetectionTest", "couldn't compile post-processing shader: " + batchShader.getLog());
}
mesh = ObjLoader.loadObj(Gdx.files.internal("data/scene.obj").read());
fbo = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0, 0, 10);
cam.lookAt(0, 0, 0);
cam.far = 30;
batch = new SpriteBatch();
batch.setShader(batchShader);
fboRegion = new TextureRegion(fbo.getColorBufferTexture());
fboRegion.flip(false, true);
logger = new FPSLogger();
calculateOffsets();
}
private void calculateOffsets() {
int idx = 0;
for(int y = -1; y <= 1; y++) {
for(int x = -1; x <= 1; x++) {
offsets[idx++] = x / (float)Gdx.graphics.getWidth();
offsets[idx++] = y / (float)Gdx.graphics.getHeight();
}
}
System.out.println(Arrays.toString(offsets));
}
public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
- batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
+ batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
logger.log();
}
}
| true | true | public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
batch.end();
logger.log();
}
| public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
logger.log();
}
|
diff --git a/easyb/src/java/org/disco/easyb/SpecificationRunner.java b/easyb/src/java/org/disco/easyb/SpecificationRunner.java
index c67d64b..603419f 100644
--- a/easyb/src/java/org/disco/easyb/SpecificationRunner.java
+++ b/easyb/src/java/org/disco/easyb/SpecificationRunner.java
@@ -1,267 +1,267 @@
package org.disco.easyb;
import groovy.lang.GroovyShell;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.disco.easyb.core.listener.DefaultListener;
import org.disco.easyb.core.listener.SpecificationListener;
import org.disco.easyb.core.report.Report;
import org.disco.easyb.core.report.ReportWriter;
import org.disco.easyb.core.report.EasybXmlReportWriter;
import org.disco.easyb.core.report.TxtStoryReportWriter;
import org.disco.easyb.core.report.TerseReportWriter;
import org.disco.easyb.core.util.ReportFormat;
import org.disco.easyb.core.util.ReportType;
import org.disco.easyb.core.util.SpecificationStepType;
import org.disco.easyb.core.SpecificationStep;
/**
* usage is:
* <p/>
* java SpecificationRunner my/path/to/spec/MyStory.groovy -txtstory ./reports/story-report.txt
* <p/>
* You don't need to pass in the file name for the report either-- if no
* path is present, then the runner will create a report in the current directory
* with a default filename following this convention: easyb-<type>-report.<format>
* <p/>
* Multiple specifications can be passed in on the command line
* <p/>
* java SpecificationRunner my/path/to/spec/MyStory.groovy my/path/to/spec/AnotherStory.groovy
*/
public class SpecificationRunner {
List<Report> reports;
public SpecificationRunner() {
this(null);
}
public SpecificationRunner(List<Report> reports) {
this.reports = addDefaultReports(reports);
}
/**
* TODO: refactor me please
*
* @param specs collection of files that contain the specifications
* @return BehaviorListener has status about failures and successes
* @throws Exception if unable to write report file
*/
public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
- System.out.println("Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
+ System.out.println((currentStep.getChildStepSpecificationFailureCount() == 0 ? "" : "FAILURE ") + "Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
private void warnOnBehaviorNaming(File file) {
if (!file.getName().contains("Behavior.groovy")) {
System.out.println("You should consider ending your specification file (" +
file.getName() + ") with either Story or Behavior. " +
"See easyb documentation for more details. ");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Options options = getOptionsForMain();
try {
CommandLine commandLine = getCommandLineForMain(args, options);
validateArguments(commandLine);
SpecificationRunner runner = new SpecificationRunner(getConfiguredReports(commandLine));
runner.runSpecification(getFileCollection(commandLine.getArgs()));
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
handleHelpForMain(options);
} catch (ParseException pe) {
System.out.println(pe.getMessage());
handleHelpForMain(options);
} catch (Exception e) {
System.err.println("There was an error running the script");
e.printStackTrace(System.err);
System.exit(-6);
}
}
private static void validateArguments(CommandLine commandLine) throws IllegalArgumentException {
if (commandLine.getArgs().length == 0) {
throw new IllegalArgumentException("Required Arguments not passed in.");
}
}
private static List<Report> getConfiguredReports(CommandLine line) {
List<Report> configuredReports = new ArrayList<Report>();
if (line.hasOption(Report.XML_BEHAVIOR)) {
Report report = new Report();
report.setFormat(ReportFormat.XML.format());
if (line.getOptionValue(Report.XML_BEHAVIOR) == null) {
report.setLocation("easyb-behavior-report.xml");
} else {
report.setLocation(line.getOptionValue(Report.XML_BEHAVIOR));
}
report.setType(ReportType.BEHAVIOR.type());
configuredReports.add(report);
}
if (line.hasOption(Report.TXT_STORY)) {
Report report = new Report();
report.setFormat(ReportFormat.TXT.format());
if (line.getOptionValue(Report.TXT_STORY) == null) {
report.setLocation("easyb-story-report.txt");
} else {
report.setLocation(line.getOptionValue(Report.TXT_STORY));
}
report.setType(ReportType.STORY.type());
configuredReports.add(report);
}
if (line.hasOption(Report.XML_EASYB)) {
Report report = new Report();
report.setFormat(ReportFormat.XML.format());
if (line.getOptionValue(Report.XML_EASYB) == null) {
report.setLocation("easyb-report.xml");
} else {
report.setLocation(line.getOptionValue(Report.XML_EASYB));
}
report.setType(ReportType.EASYB.type());
configuredReports.add(report);
}
return configuredReports;
}
/**
* @param paths locations of the specifications to be loaded
* @return collection of files where the only element is the file of the spec to be run
*/
private static Collection<File> getFileCollection(String[] paths) {
Collection<File> coll = new ArrayList<File>();
for (String path : paths) {
coll.add(new File(path));
}
return coll;
}
/**
* @param options options that are available to this specification runner
*/
private static void handleHelpForMain(Options options) {
new HelpFormatter().printHelp("SpecificationRunner my/path/to/MyStory.groovy", options);
}
/**
* @param args command line arguments passed into main
* @param options options that are available to this specification runner
* @return representation of command line arguments passed in that match the available options
* @throws ParseException if there are any problems encountered while parsing the command line tokens
*/
private static CommandLine getCommandLineForMain(String[] args, Options options) throws ParseException {
CommandLineParser commandLineParser = new GnuParser();
return commandLineParser.parse(options, args);
}
/**
* @return representation of a collection of Option objects, which describe the possible options for a command-line.
*/
private static Options getOptionsForMain() {
Options options = new Options();
//noinspection AccessStaticViaInstance
Option xmleasybreport = OptionBuilder.withArgName("file").hasArg()
.withDescription("create an easyb report in xml format").create(Report.XML_EASYB);
options.addOption(xmleasybreport);
//noinspection AccessStaticViaInstance
// Option xmlbehaviorreport = OptionBuilder.withArgName("file").hasArg()
// .withDescription("create a behavior report in xml format").create(Report.XML_BEHAVIOR);
// options.addOption(xmlbehaviorreport);
//noinspection AccessStaticViaInstance
Option storyreport = OptionBuilder.withArgName("file").hasArg()
.withDescription("create a story report").create(Report.TXT_STORY);
options.addOption(storyreport);
return options;
}
private List<Report> addDefaultReports(List<Report> userConfiguredReports) {
List<Report> configuredReports = new ArrayList<Report>();
if (userConfiguredReports != null) {
configuredReports.addAll(userConfiguredReports);
}
return configuredReports;
}
}
| true | true | public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
System.out.println("Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
| public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
System.out.println((currentStep.getChildStepSpecificationFailureCount() == 0 ? "" : "FAILURE ") + "Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
|
diff --git a/common/num/numirp/core/handlers/TickHandler.java b/common/num/numirp/core/handlers/TickHandler.java
index ec16efe..784d302 100644
--- a/common/num/numirp/core/handlers/TickHandler.java
+++ b/common/num/numirp/core/handlers/TickHandler.java
@@ -1,48 +1,48 @@
package num.numirp.core.handlers;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import num.numirp.core.util.ImageDownload;
import num.numirp.lib.Reference;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
public class TickHandler implements ITickHandler {
private static final Minecraft mc = Minecraft.getMinecraft();
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
- if (player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
+ if (player != null && player.cloakUrl != null && player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.CLIENT);
}
@Override
public String getLabel() {
return "NumiRP.TickHandler";
}
}
| true | true | public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
if (player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
| public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
if (player != null && player.cloakUrl != null && player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
|
diff --git a/test/policy/WSSPolicyTesterAsymm.java b/test/policy/WSSPolicyTesterAsymm.java
index 988dd2e8a..c2ee748ad 100644
--- a/test/policy/WSSPolicyTesterAsymm.java
+++ b/test/policy/WSSPolicyTesterAsymm.java
@@ -1,425 +1,425 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package policy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.AxisClient;
import org.apache.axis.configuration.NullProvider;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.utils.XMLUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.SOAPConstants;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.WSSecurityEngine;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.message.WSSecEncrypt;
import org.apache.ws.security.message.WSSecHeader;
import org.apache.ws.security.message.WSSecTimestamp;
import org.apache.ws.security.message.WSSecSignature;
import org.apache.ws.security.policy.Constants;
import org.apache.ws.security.policy.WSS4JPolicyBuilder;
import org.apache.ws.security.policy.WSS4JPolicyData;
import org.apache.ws.security.policy.WSS4JPolicyToken;
import org.apache.ws.security.policy.WSSPolicyException;
import org.apache.ws.security.policy.model.RootPolicyEngineData;
import org.apache.ws.security.policy.parser.WSSPolicyProcessor;
import org.apache.ws.security.util.WSSecurityUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import wssec.SOAPUtil;
public class WSSPolicyTesterAsymm extends TestCase implements CallbackHandler {
private static Log log = LogFactory.getLog(WSSPolicyTesterAsymm.class);
static final String soapMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ " <soapenv:Body>"
+ " <ns1:testMethod xmlns:ns1=\"uri:LogTestService2\"></ns1:testMethod>"
+ " </soapenv:Body>" + "</soapenv:Envelope>";
static final WSSecurityEngine secEngine = new WSSecurityEngine();
static final Crypto crypto = CryptoFactory.getInstance();
static final Crypto cryptoSKI = CryptoFactory
.getInstance("cryptoSKI.properties");
MessageContext msgContext;
Message message;
/**
* Policy Tester constructor.
*
* @param name
* name of the test
*/
public WSSPolicyTesterAsymm(String name) {
super(name);
}
/**
* JUnit suite <p/>
*
* @return a junit test suite
*/
public static Test suite() {
return new TestSuite(WSSPolicyTesterAsymm.class);
}
/**
* Main method
*
* @param args
* command line args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
/**
* Setup method.
*
* Initializes an Axis 1 environment to process SOAP messages
*
* @throws Exception
* Thrown when there is a problem in setup
*/
protected void setUp() throws Exception {
AxisClient tmpEngine = new AxisClient(new NullProvider());
msgContext = new MessageContext(tmpEngine);
message = getSOAPMessage();
}
/**
* Constructs a soap envelope.
*
* @return A SOAP envelope
* @throws Exception
* if there is any problem constructing the soap envelope
*/
protected Message getSOAPMessage() throws Exception {
InputStream in = new ByteArrayInputStream(soapMsg.getBytes());
Message msg = new Message(in);
msg.setMessageContext(msgContext);
return msg;
}
public void testerAsymm() {
try {
WSSPolicyProcessor processor = new WSSPolicyProcessor();
if (!processor.setup()) {
return;
}
String[] files = new String[2];
files[0] = "test/policy/SecurityPolicyBindingsAsymmTest.xml";
files[1] = "test/policy/SecurityPolicyMsgTest.xml";
processor.go(files);
RootPolicyEngineData rootPolicyEngineData = (RootPolicyEngineData) processor.secProcessorContext
.popPolicyEngineData();
assertNotNull("RootPolicyEngineData missing", rootPolicyEngineData);
ArrayList peds = rootPolicyEngineData.getTopLevelPEDs();
log.debug("Number of top level PolicyEngineData: " + peds.size());
WSS4JPolicyData wpd = WSS4JPolicyBuilder.build(peds);
createMessageAsymm(wpd);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail(e.getMessage());
} catch (WSSPolicyException e) {
e.printStackTrace();
fail(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
- recEncrypt.setKeyIdentifierType(recToken.getEncKeyIdentifier());
+ recEncrypt.setKeyIdentifierType(recToken.getKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
- iniSignature.setKeyIdentifierType(iniToken.getSigKeyIdentifier());
+ iniSignature.setKeyIdentifierType(iniToken.getKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
/**
* Verifies the soap envelope <p/>
*
* @param envelope
* @throws Exception
* Thrown when there is a problem in verification
*/
private void verify(Document doc) throws Exception {
secEngine.processSecurityHeader(doc, null, this, crypto, cryptoSKI);
SOAPUtil.updateSOAPMessage(doc, message);
String decryptedString = message.getSOAPPartAsString();
assertTrue(decryptedString.indexOf("LogTestService2") > 0 ? true
: false);
}
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
/*
* here call a function/method to lookup the password for the
* given identifier (e.g. a user name or keystore alias) e.g.:
* pc.setPassword(passStore.getPassword(pc.getIdentfifier)) for
* Testing we supply a fixed name here.
*/
pc.setPassword("security");
} else {
throw new UnsupportedCallbackException(callbacks[i],
"Unrecognized Callback");
}
}
}
}
| false | true | private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
recEncrypt.setKeyIdentifierType(recToken.getEncKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
iniSignature.setKeyIdentifierType(iniToken.getSigKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
| private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
recEncrypt.setKeyIdentifierType(recToken.getKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
iniSignature.setKeyIdentifierType(iniToken.getKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
|
diff --git a/src/de/aidger/model/AbstractModel.java b/src/de/aidger/model/AbstractModel.java
index 9b364815..06982cb6 100644
--- a/src/de/aidger/model/AbstractModel.java
+++ b/src/de/aidger/model/AbstractModel.java
@@ -1,434 +1,435 @@
package de.aidger.model;
import static de.aidger.utils.Translation._;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Vector;
import de.aidger.model.validators.DateRangeValidator;
import de.aidger.model.validators.EmailValidator;
import de.aidger.model.validators.InclusionValidator;
import de.aidger.model.validators.PresenceValidator;
import de.aidger.model.validators.Validator;
import de.aidger.utils.Logger;
import de.unistuttgart.iste.se.adohive.controller.AdoHiveController;
import de.unistuttgart.iste.se.adohive.controller.IAdoHiveManager;
import de.unistuttgart.iste.se.adohive.exceptions.AdoHiveException;
import de.unistuttgart.iste.se.adohive.model.IAdoHiveModel;
/**
* AbstractModel contains all important database related functions which all
* models need to contain. This includes getting instances of models and saving
* or removing them.
*
* @author Philipp Gildein
*/
public abstract class AbstractModel<T> extends Observable implements
IAdoHiveModel<T> {
/**
* The unique id of the model in the database.
*/
protected int id = 0;
/**
* Determines if the model has been saved in the db yet.
*/
protected boolean isNew = true;
/**
* Should the model first be removed before saveing. Needed for example for
* HourlyWage which has several Primary Keys and needs to be removed when
* edited.
*/
protected boolean removeOnUpdate = false;
/**
* Used to cache the AdoHiveManagers after getting them the first time.
*/
protected static Map<String, IAdoHiveManager> managers =
new HashMap<String, IAdoHiveManager>();
/**
* Array containing all validators for that specific model.
*/
protected List<Validator> validators = new Vector<Validator>();
/**
* Array containing errors if a validator fails.
*/
protected List<String> errors = new Vector<String>();
/**
* Map of errors for specific fields.
*/
protected Map<String, List<String>> fieldErrors = new HashMap<String, List<String>>();
/**
* Cloneable function inherited from IAdoHiveModel.
*
* @return Clone of the model
*/
@Override
abstract public T clone();
/**
* Get all models from the database.
*
* @return An array containing all found models or null
*/
@SuppressWarnings("unchecked")
public List getAll() throws AdoHiveException {
return getManager().getAll();
}
/**
* Get a specific model by specifying its unique id.
*
* @param id
* The unique id of the model
* @return The model if one was found or null
*/
@SuppressWarnings("unchecked")
public T getById(int id) throws AdoHiveException {
return (T) getManager().getById(id);
}
/**
* Get a specific model by specifying a set of keys.
*
* @param o
* The set of keys specific to this model
* @return The model if one was found or null
*/
@SuppressWarnings("unchecked")
public T getByKeys(Object... o) throws AdoHiveException {
return (T) getManager().getByKeys(o);
}
/**
* Get the number of models in the database.
*
* @return The number of models
* @throws AdoHiveException
*/
public int size() throws AdoHiveException {
return getManager().size();
}
/**
* Returns true if no model has been saved into the database.
*
* @return True if no model is in the database
* @throws AdoHiveException
*/
public boolean isEmpty() throws AdoHiveException {
return getManager().isEmpty();
}
/**
* Checks if the current instance exists in the database.
*
* @return True if the instance exists
* @throws AdoHiveException
*/
public boolean isInDatabase() throws AdoHiveException {
return getManager().contains(this);
}
/**
* Deletes everything from the associated table.
*
* @throws AdoHiveException
*/
public void clearTable() throws AdoHiveException {
getManager().clear();
id = 0; // Reset
}
// TODO: Add get(index) method?
/**
* Save the current model to the database.
*
* @return True if validation succeeds
* @throws AdoHiveException
*/
@SuppressWarnings("unchecked")
public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
+ setNew(false);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
/**
* Remove the current model from the database.
*
* @throws AdoHiveException
*/
@SuppressWarnings("unchecked")
public void remove() throws AdoHiveException {
if (!isNew) {
getManager().remove(this);
clearChanged();
notifyObservers();
setNew(true);
}
}
/**
* Get a list of all errors.
*
* @return A list of errors
*/
public List<String> getErrors() {
return errors;
}
/**
* Get a list of errors for a specific field.
*
* @param field
* The field to get the errors for
* @return A list of errors
*/
public List<String> getErrorsFor(String field) {
return fieldErrors.get(field);
}
/**
* Add an error to the list,
*
* @param error
* The error to add
*/
public void addError(String error) {
errors.add(error);
}
/**
* Add an error for a specific field to the list.
*
* @param field
* The field on which the error occured
* @param error
* The error to add
*/
public void addError(String field, String error) {
error = field + " " + error;
errors.add(error);
if (fieldErrors.containsKey(field)) {
fieldErrors.get(field).add(error);
} else {
List<String> list = new Vector<String>();
list.add(error);
fieldErrors.put(field, list);
}
}
/**
* Clear the error lists.
*/
public void resetErrors() {
errors.clear();
fieldErrors.clear();
}
/**
* Add a validator to the model.
*
* @param valid
* The validator to add
*/
public void addValidator(Validator valid) {
validators.add(valid);
}
/**
* Add a presence validator to the model.
*
* @param members
* The name of the member variables to validate
*/
public void validatePresenceOf(String[] members) {
validators.add(new PresenceValidator(this, members));
}
/**
* Add an email validator to the model.
*
* @param member
* The name of the member variable to validate
*/
public void validateEmailAddress(String member) {
validators.add(new EmailValidator(this, new String[] { member }));
}
/**
* Add an date range validator to the model.
*
* @param from
* The starting date
* @param to
* The end date
*/
public void validateDateRange(String from, String to) {
validators.add(new DateRangeValidator(this, from, to));
}
/**
* Add an inclusion validator to the model.
*
* @param members
* The name of the member variables to validate
* @param inc
* The list to check for inclusion
*/
public void validateInclusionOf(String[] members, String[] inc) {
validators.add(new InclusionValidator(this, members, inc));
}
/**
* Returns the unique id of the activity.
*
* @return The unique id of the activity
*/
@Override
public int getId() {
return id;
}
/**
* Set the unique id of the assistant.
*
* <b>!!! THIS IS FOR INTERNAL ADOHIVE USAGE ONLY !!!</b>
*
* @param id
* The unique id of the assistant
*/
@Override
public void setId(int id) {
this.id = id;
}
/**
* Set if the model is new and should be added to the database.
*
* @param isnew
* Is the model new?
*/
public void setNew(boolean isnew) {
isNew = isnew;
if (isNew) {
setId(0);
}
}
/**
* Returns a string containing all informations stored in the model.
*
* @return A string containing informations on the model
*/
@Override
public String toString() {
String ret = getClass().getSimpleName() + " [" + "ID: " + getId()
+ ", ";
try {
for (java.lang.reflect.Method m : getClass().getDeclaredMethods()) {
if (m.getName().startsWith("get")
&& m.getParameterTypes().length == 0) {
ret += m.getName().substring(3) + ": ";
ret += m.invoke(this, new Object[0]) + ", ";
}
}
if (ret.endsWith(", ")) {
ret = ret.substring(0, ret.length() - 2);
}
} catch (InvocationTargetException ex) {
System.err.println(ex.getMessage());
} catch (IllegalArgumentException ex) {
System.err.println(ex.getMessage());
} catch (IllegalAccessException ex) {
System.err.println(ex.getMessage());
}
return ret + "]";
}
/**
* Extract the name of the class and return the correct manager.
*
* @return The name of the model class
*/
@SuppressWarnings("unchecked")
protected IAdoHiveManager getManager() {
String classname = getClass().getSimpleName();
if (!managers.containsKey(classname) ||
managers.get(classname) == null) {
/* Try to get the correct manager from the AdoHiveController */
try {
java.lang.reflect.Method m = AdoHiveController.class
.getMethod("get" + classname + "Manager");
managers.put(classname, (IAdoHiveManager) m.invoke(
AdoHiveController.getInstance(), new Object[0]));
} catch (Exception ex) {
Logger.error(MessageFormat.format(
_("Could not get manager for class \"{0}\". Error: {1}"),
new Object[] { classname, ex.getMessage() }));
}
}
return managers.get(classname);
}
/**
* Validate the input using the validators and a custom validate function.
*
* @return True if everything validates
*/
protected boolean doValidate() {
/* Try to validate before adding/updating */
boolean ret = true;
for (Validator v : validators) {
if (!v.validate()) {
ret = false;
}
}
/* Check if the model got a validate() function */
try {
java.lang.reflect.Method m = getClass().getDeclaredMethod(
"validate");
if (!(Boolean) m.invoke(this, new Object[0])) {
ret = false;
}
} catch (Exception ex) {
}
return ret;
}
}
| true | true | public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
| public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
setNew(false);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
|
diff --git a/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java b/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
index 06b425c4..2a976f23 100644
--- a/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
+++ b/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
@@ -1,83 +1,83 @@
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.editor.inspections.bugs;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.sylvanaar.idea.Lua.editor.inspections.AbstractInspection;
import com.sylvanaar.idea.Lua.lang.psi.LuaPsiFile;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaDeclarationExpression;
import com.sylvanaar.idea.Lua.lang.psi.statements.LuaBlock;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaGlobal;
import com.sylvanaar.idea.Lua.lang.psi.visitor.LuaElementVisitor;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 7/4/11
* Time: 10:11 AM
*/
public class GlobalCreationOutsideOfMainChunk extends AbstractInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Suspicious global creation";
}
@Override
public String getStaticDescription() {
return "Looks for creation of globals in scopes other than the main chunk";
}
@NotNull
@Override
public String getGroupDisplayName() {
return PROBABLE_BUGS;
}
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.WARNING;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
- LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class, LuaPsiFile.class);
+ LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class);
if (block == null) return;
- if (block.getParent() instanceof LuaPsiFile)
+ if (block instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
}
| false | true | public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class, LuaPsiFile.class);
if (block == null) return;
if (block.getParent() instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
| public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class);
if (block == null) return;
if (block instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
|
diff --git a/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java b/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java
index dc5626fe..be890862 100644
--- a/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java
+++ b/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java
@@ -1,548 +1,548 @@
package org.geopublishing.geopublisher.swing;
/*******************************************************************************
* Copyright (c) 2010 Stefan A. Tzeggai.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Stefan A. Tzeggai - initial API and implementation
******************************************************************************/
import java.awt.Component;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.geopublishing.atlasViewer.AVProps;
import org.geopublishing.atlasViewer.AtlasConfig;
import org.geopublishing.atlasViewer.AtlasRefInterface;
import org.geopublishing.atlasViewer.dp.DpEntry;
import org.geopublishing.atlasViewer.dp.DpRef;
import org.geopublishing.atlasViewer.dp.Group;
import org.geopublishing.atlasViewer.dp.layer.DpLayer;
import org.geopublishing.atlasViewer.dp.media.DpMedia;
import org.geopublishing.atlasViewer.exceptions.AtlasImportException;
import org.geopublishing.atlasViewer.map.Map;
import org.geopublishing.atlasViewer.swing.AVSwingUtil;
import org.geopublishing.atlasViewer.swing.AtlasSwingWorker;
import org.geopublishing.geopublisher.AMLExporter;
import org.geopublishing.geopublisher.AtlasConfigEditable;
import org.geopublishing.geopublisher.GpUtil;
import org.geopublishing.geopublisher.gui.internal.GPDialogManager;
import schmitzm.io.IOUtil;
import schmitzm.jfree.chart.style.ChartStyle;
import schmitzm.lang.LangUtil;
import schmitzm.swing.ExceptionDialog;
import schmitzm.swing.SwingUtil;
import skrueger.i8n.I8NUtil;
public class GpSwingUtil extends GpUtil {
private static final Logger LOGGER = Logger.getLogger(GpSwingUtil.class);
/**
* Deletes a {@link DpEntry}. This deletes the Entry from the Atlas'
* datapool, as well as all references to it, as well as the folder on disk.
*
* @param ace
* {@link AtlasConfigEditable} where the {@link DpEntry} is part
* of.
* @param dpe
* {@link DpEntry} to be deleted.
* @param askUserToVerify
* If <code>true</code>, the user will be asked for confirmation.
* The confirmation will list all references. If
* <code>false</code>, the DPE and all references are
* automatically removed.
*
* @return <code>null</code> if the deletion failed or was aborted by the
* user. Otherwise the removed {@link DpEntry}.
*/
public static DpEntry<?> deleteDpEntry(Component owner,
AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) {
LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>();
// ****************************************************************************
// Go through all mapPoolEntries and groups and count the references to
// this DatapoolEntry
// ****************************************************************************
Set<Map> mapsWithReferences = new HashSet<Map>();
for (Map map : ace.getMapPool().values()) {
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
map.getAdditionalStyles().remove(dpe.getId());
map.getSelectedStyleIDs().remove(dpe.getId());
}
int countRefsInMappool = references.size();
// ****************************************************************************
// Go through all group tree count the references to this DatapoolEntry
// ****************************************************************************
Group group = ace.getFirstGroup();
Group.findReferencesTo(group, dpe, references, false);
if (askUserToVerify) {
// Ask the user if she still wants to delete the DPE, even though
// references exist.
int res = JOptionPane.showConfirmDialog(owner, GpUtil.R(
"DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe
.getFilename(), countRefsInMappool, LangUtil
.stringConcatWithSep(", ", mapsWithReferences),
references.size() - countRefsInMappool, dpe.getTitle()
.toString()), GpUtil
.R("DataPoolWindow_Action_DeleteDPE_label" + " "
+ dpe.getTitle()), JOptionPane.YES_NO_OPTION);
- if (res == JOptionPane.NO_OPTION)
+ if (res != JOptionPane.YES_OPTION)
return null;
}
// Close all dialogs that use this layer
if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe))
return null;
// ****************************************************************************
// Delete the references first. Kill DesignMapViewJDialogs if affected.
// Abort everything if the user doesn't want to close the
// DesignMapViewJDialog.
// ****************************************************************************
for (Map map : ace.getMapPool().values()) {
boolean affected = false;
// Check all the layers
final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>();
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (!ref.getTargetId().equals(dpe.getId()))
layersNew.add(ref);
else {
affected = true;
}
}
// Check all the media
final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>();
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (!ref.getTargetId().equals(dpe.getId()))
mediaNew.add(ref);
else {
affected = true;
}
}
// Close any open DesignMapViewJDialogs or abort if the user doesn't
// want to close.
if (affected) {
if (!GPDialogManager.dm_MapComposer.close(map))
return null;
}
// Now we change this map
map.setLayers(layersNew);
map.setMedia(mediaNew);
}
Group.findReferencesTo(group, dpe, references, true);
final File dir = new File(ace.getDataDir(), dpe.getDataDirname());
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
ExceptionDialog.show(owner, e);
}
return ace.getDataPool().remove(dpe.getId());
}
/**
* Checks if a filename is OK for the AV. Asks the use to accespt the
* changed name
*
* @param owner
* GUI owner
* @param nameCandidate
* Filename to check, e.g. bahn.jpg
* @return <code>null</code> if the user didn't accept the new filename.
*
* @throws AtlasImportException
* if the user doesn't like the change of the filename.
*/
public static String cleanFilenameWithUI(Component owner,
String nameCandidate) throws AtlasImportException {
String cleanName = IOUtil.cleanFilename(nameCandidate);
if (!cleanName.equals(nameCandidate)) {
/**
* The candidate was not clean. Ask the user to accept the new name
* or cancel.
*/
if (!AVSwingUtil.askOKCancel(owner,
R("Cleanfile.Question", nameCandidate, cleanName))) {
throw new AtlasImportException(R(
"Cleanfile.Denied.ImportCancelled", nameCandidate));
}
}
return cleanName;
}
/**
* Validates, that all directory references actually exist. If some
* directory is missing, asks the user if he want's to delete the entry and
* all references to it.<br/>
* Also checks that all directories in <code>ad/data</code> folder are
* actually referenced. If now, the used is asked to delete the folder.</br>
* This method also initializes the size-cache for every {@link DpEntry}.
*/
public static void validate(AtlasConfigEditable ace, final Component owner) {
LOGGER.debug("starting validation of datatpool");
LinkedList<DpEntry<?>> errorEntries = new LinkedList<DpEntry<?>>();
// ****************************************************************************
// First collect all erroneous DpEntries...
// ****************************************************************************
for (DpEntry<?> dpe : ace.getDataPool().values()) {
File dir = new File(ace.getDataDir(), dpe.getDataDirname());
// Checking for possible errors...
if (!dir.exists() || !dir.isDirectory()) {
errorEntries.add(dpe);
} else {
// Calculate the size of the folder now and cache it for
// later...
ace.getFolderSize(dpe);
}
}
// ****************************************************************************
// ... now delete them. (We should not modify a datapool that we are
// iterating through.
// ****************************************************************************
for (final DpEntry<?> dpe : errorEntries) {
final String msg1 = GpUtil.R(
"AtlasLoader.Validation.dpe.invalid.msg", dpe.getTitle(),
dpe.getId());
final String msg2 = GpUtil.R(
"AtlasLoader.Validation.dpe.invalid.msg.folderDoesnExist",
new File(ace.getDataDir(), dpe.getDataDirname())
.getAbsolutePath());
final String question = GpUtil
.R("AtlasLoader.Validation.dpe.invalid.msg.exitOrRemoveQuestion");
if (AVSwingUtil.askYesNo(owner, msg1 + "\n" + msg2 + "\n"
+ question)) {
deleteDpEntry(owner, ace, dpe, false);
}
}
cleanFolder(ace, owner);
}
/**
* Checks the data dir folder of the {@link AtlasConfigEditable} and asks to
* delete any unexpected folders.
*
* @param owner
* if <code>null</code> all files will be deleted automatically
*/
public static void cleanFolder(AtlasConfigEditable ace,
final Component owner) {
// ****************************************************************************
// now list all directories in ad/html and check whether they are
// actually used
// ****************************************************************************
for (File dir : ace.getHtmlDir().listFiles()) {
if (!dir.isDirectory())
continue;
if (dir.getName().startsWith("."))
continue;
// if (dir.getName().equals(AtlasConfigEditable.IMAGES_DIRNAME))
// continue;
if (dir.getName().equals(AtlasConfigEditable.ABOUT_DIRNAME))
continue;
boolean isReferenced = false;
for (Map map : ace.getMapPool().values()) {
if (ace.getHtmlDirFor(map).getName().equals(dir.getName())) {
isReferenced = true;
break;
}
}
if (isReferenced)
continue;
LOGGER.info("The map directory " + IOUtil.escapePath(dir)
+ " is not referenced in the atlas.");
askToDeleteUnreferencedFolder(ace.getHtmlDir(), owner, dir);
}
// ****************************************************************************
// now list all directories in ad/data and check whether they are
// actually used
// ****************************************************************************
for (File dir : ace.getDataDir().listFiles()) {
if (!dir.isDirectory())
continue;
if (dir.getName().startsWith(".")) {
continue;
}
boolean isReferenced = false;
for (DpEntry<?> dpe : ace.getDataPool().values()) {
if (dpe.getDataDirname().equals(dir.getName())) {
isReferenced = true;
break;
}
}
if (isReferenced)
continue;
LOGGER.info("The directory " + IOUtil.escapePath(dir)
+ " is not referenced in the atlas.");
askToDeleteUnreferencedFolder(ace.getDataDir(), owner, dir);
}
}
/**
* Asks to delete a file or folder and returns <code>true</code> if the file
* has been deleted.
*/
private static boolean askToDeleteUnreferencedFolder(File dir,
final Component owner, File d) {
boolean askDelete = true;
if (owner != null)
askDelete = AVSwingUtil
.askOKCancel(
owner,
GpSwingUtil
.R("UnreferencedDirectoryFoundInAtlasDataDir_AskIfItShouldBeDeleted",
IOUtil.escapePath(dir), d.getName()));
if (askDelete) {
if (owner != null)
LOGGER.info("User allowed to delete folder "
+ IOUtil.escapePath(d) + ".");
else
LOGGER.info("Automatically delete folder "
+ IOUtil.escapePath(d) + ".");
if ((d.isDirectory() && new File(d, ".svn").exists())) {
LOGGER.info("Please use:\nsvn del \"" + IOUtil.escapePath(d)
+ "\" && svn commit \"" + IOUtil.escapePath(d)
+ "\" -m \"deleted an unused directory\"");
if (owner != null)
AVSwingUtil
.showMessageDialog(
owner,
GpSwingUtil
.R("UnreferencedDirectoryFoundInAtlasDataDir_WillNotBeDeletedDueToSvnButOfferTheCommand",
d.getName(),
IOUtil.escapePath(d)));
} else {
// Just delete the directory!
return FileUtils.deleteQuietly(d);
}
}
return false;
}
/**
* Save the {@link AtlasConfig} to its project directory
*
* @param parentGUI
* If not <code>null</code>, the user get's feedback message
* SaveAtlas.Success.Message
*
* @return false Only if there happened an error while saving. If there is
* nothing to save, returns true;
*/
public static boolean save(final AtlasConfigEditable ace,
final Component parentGUI, boolean confirm) {
SwingUtil.checkOnEDT();
;
AtlasSwingWorker<Boolean> swingWorker = new AtlasSwingWorker<Boolean>(
parentGUI) {
@Override
protected Boolean doInBackground() throws Exception {
AMLExporter amlExporter = new AMLExporter(ace);
if (amlExporter.saveAtlasConfigEditable(statusDialog)) {
ace.getProperties().save(
new File(ace.getAtlasDir(),
AVProps.PROPERTIESFILE_RESOURCE_NAME));
new File(ace.getAtlasDir(),
AtlasConfigEditable.ATLAS_GPA_FILENAME)
.createNewFile();
return true;
}
return false;
}
};
try {
Boolean saved = swingWorker.executeModal();
if (saved && confirm) {
JOptionPane.showMessageDialog(parentGUI,
GeopublisherGUI.R("SaveAtlas.Success.Message"));
}
return saved;
} catch (Exception e) {
ExceptionDialog.show(parentGUI, e);
return false;
}
}
/**
* Returns a {@link List} of {@link File}s that point to the HTML info files
* of a DpLayer. The order of the {@link File}s in the {@link List} is equal
* to the order of the languages.<br/>
* All HTML files returned to exist! If they don't exist they are being
* created with a default text.
*
* @param dpl
* {@link DpLayer} that the HTML files belong to.
*/
static public List<File> getHTMLFilesFor(
DpLayer<?, ? extends ChartStyle> dpl) {
List<File> htmlFiles = new ArrayList<File>();
AtlasConfigEditable ac = (AtlasConfigEditable) dpl.getAtlasConfig();
File dir = new File(ac.getDataDir(), dpl.getDataDirname());
for (String lang : ac.getLanguages()) {
try {
File htmlFile = new File(
(FilenameUtils.removeExtension(new File(dir, dpl
.getFilename()).getCanonicalPath())
+ "_"
+ lang + ".html"));
if (!htmlFile.exists()) {
LOGGER.info("Creating a default info HTML file for dpe "
+ dpl.getTitle() + "\n at "
+ htmlFile.getAbsolutePath());
/**
* Create a default HTML About window
*/
FileWriter fw = new FileWriter(htmlFile);
fw.write(GpUtil.R("DPLayer.HTMLInfo.DefaultHTMLFile",
I8NUtil.getFirstLocaleForLang(lang)
.getDisplayLanguage(), dpl.getTitle()));
fw.flush();
fw.close();
}
htmlFiles.add(htmlFile);
} catch (IOException e) {
LOGGER.error(e);
ExceptionDialog.show(GeopublisherGUI.getInstance().getJFrame(),
e);
}
}
return htmlFiles;
}
/**
* Returns a {@link List} of {@link File}s that point to the HTML info
* filesfor a {@link Map}. The order of the {@link File}s in the
* {@link List} is equal to the order of the languages.<br/>
* All HTML files returned to exist! If they don't exist they are being
* created with a default text.
*
* @param dpl
* {@link DpLayer} that the HTML files belong to.
*/
public static List<File> getHTMLFilesFor(Map map) {
List<File> htmlFiles = new ArrayList<File>();
AtlasConfigEditable ace = (AtlasConfigEditable) map.getAc();
File dir = new File(ace.getHtmlDir(), map.getId());
dir.mkdirs();
for (String lang : ace.getLanguages()) {
try {
File htmlFile = new File(new File(dir, "index" + "_" + lang
+ ".html").getCanonicalPath());
if (!htmlFile.exists()) {
LOGGER.info("Creating a default info HTML file for map "
+ map.getTitle() + "\n at "
+ htmlFile.getAbsolutePath());
/**
* Create a default HTML About window
*/
FileWriter fw = new FileWriter(htmlFile);
fw.write(GpUtil.R("Map.HTMLInfo.DefaultHTMLFile", I8NUtil
.getFirstLocaleForLang(lang).getDisplayLanguage(),
map.getTitle()));
fw.flush();
fw.close();
}
htmlFiles.add(htmlFile);
} catch (IOException e) {
LOGGER.error(e);
ExceptionDialog.show(GeopublisherGUI.getInstance().getJFrame(),
e);
}
}
return htmlFiles;
}
}
| true | true | public static DpEntry<?> deleteDpEntry(Component owner,
AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) {
LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>();
// ****************************************************************************
// Go through all mapPoolEntries and groups and count the references to
// this DatapoolEntry
// ****************************************************************************
Set<Map> mapsWithReferences = new HashSet<Map>();
for (Map map : ace.getMapPool().values()) {
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
map.getAdditionalStyles().remove(dpe.getId());
map.getSelectedStyleIDs().remove(dpe.getId());
}
int countRefsInMappool = references.size();
// ****************************************************************************
// Go through all group tree count the references to this DatapoolEntry
// ****************************************************************************
Group group = ace.getFirstGroup();
Group.findReferencesTo(group, dpe, references, false);
if (askUserToVerify) {
// Ask the user if she still wants to delete the DPE, even though
// references exist.
int res = JOptionPane.showConfirmDialog(owner, GpUtil.R(
"DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe
.getFilename(), countRefsInMappool, LangUtil
.stringConcatWithSep(", ", mapsWithReferences),
references.size() - countRefsInMappool, dpe.getTitle()
.toString()), GpUtil
.R("DataPoolWindow_Action_DeleteDPE_label" + " "
+ dpe.getTitle()), JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.NO_OPTION)
return null;
}
// Close all dialogs that use this layer
if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe))
return null;
// ****************************************************************************
// Delete the references first. Kill DesignMapViewJDialogs if affected.
// Abort everything if the user doesn't want to close the
// DesignMapViewJDialog.
// ****************************************************************************
for (Map map : ace.getMapPool().values()) {
boolean affected = false;
// Check all the layers
final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>();
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (!ref.getTargetId().equals(dpe.getId()))
layersNew.add(ref);
else {
affected = true;
}
}
// Check all the media
final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>();
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (!ref.getTargetId().equals(dpe.getId()))
mediaNew.add(ref);
else {
affected = true;
}
}
// Close any open DesignMapViewJDialogs or abort if the user doesn't
// want to close.
if (affected) {
if (!GPDialogManager.dm_MapComposer.close(map))
return null;
}
// Now we change this map
map.setLayers(layersNew);
map.setMedia(mediaNew);
}
Group.findReferencesTo(group, dpe, references, true);
final File dir = new File(ace.getDataDir(), dpe.getDataDirname());
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
ExceptionDialog.show(owner, e);
}
return ace.getDataPool().remove(dpe.getId());
}
| public static DpEntry<?> deleteDpEntry(Component owner,
AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) {
LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>();
// ****************************************************************************
// Go through all mapPoolEntries and groups and count the references to
// this DatapoolEntry
// ****************************************************************************
Set<Map> mapsWithReferences = new HashSet<Map>();
for (Map map : ace.getMapPool().values()) {
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (ref.getTargetId().equals(dpe.getId())) {
references.add(ref);
mapsWithReferences.add(map);
}
}
map.getAdditionalStyles().remove(dpe.getId());
map.getSelectedStyleIDs().remove(dpe.getId());
}
int countRefsInMappool = references.size();
// ****************************************************************************
// Go through all group tree count the references to this DatapoolEntry
// ****************************************************************************
Group group = ace.getFirstGroup();
Group.findReferencesTo(group, dpe, references, false);
if (askUserToVerify) {
// Ask the user if she still wants to delete the DPE, even though
// references exist.
int res = JOptionPane.showConfirmDialog(owner, GpUtil.R(
"DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe
.getFilename(), countRefsInMappool, LangUtil
.stringConcatWithSep(", ", mapsWithReferences),
references.size() - countRefsInMappool, dpe.getTitle()
.toString()), GpUtil
.R("DataPoolWindow_Action_DeleteDPE_label" + " "
+ dpe.getTitle()), JOptionPane.YES_NO_OPTION);
if (res != JOptionPane.YES_OPTION)
return null;
}
// Close all dialogs that use this layer
if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe))
return null;
// ****************************************************************************
// Delete the references first. Kill DesignMapViewJDialogs if affected.
// Abort everything if the user doesn't want to close the
// DesignMapViewJDialog.
// ****************************************************************************
for (Map map : ace.getMapPool().values()) {
boolean affected = false;
// Check all the layers
final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>();
for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) {
if (!ref.getTargetId().equals(dpe.getId()))
layersNew.add(ref);
else {
affected = true;
}
}
// Check all the media
final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>();
for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) {
if (!ref.getTargetId().equals(dpe.getId()))
mediaNew.add(ref);
else {
affected = true;
}
}
// Close any open DesignMapViewJDialogs or abort if the user doesn't
// want to close.
if (affected) {
if (!GPDialogManager.dm_MapComposer.close(map))
return null;
}
// Now we change this map
map.setLayers(layersNew);
map.setMedia(mediaNew);
}
Group.findReferencesTo(group, dpe, references, true);
final File dir = new File(ace.getDataDir(), dpe.getDataDirname());
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
ExceptionDialog.show(owner, e);
}
return ace.getDataPool().remove(dpe.getId());
}
|
diff --git a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
index 0f55423..d49efdc 100644
--- a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
+++ b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
@@ -1,138 +1,138 @@
package com.github.dreadslicer.tekkitrestrict;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
public class TRNoDupe {
@SuppressWarnings("unused")
private static boolean preventAlcDupe, preventRMDupe, preventTransmuteDupe;
public static int dupeAttempts = 0;
public static String lastPlayer = "";
public static void reload() {
preventAlcDupe = tekkitrestrict.config.getBoolean("PreventAlcDupe");
preventRMDupe = tekkitrestrict.config
.getBoolean("PreventRMFurnaceDupe");
preventTransmuteDupe = tekkitrestrict.config
.getBoolean("PreventTransmuteDupe");
}
public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
- tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
+ //tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
public static void handleDropDupes(
org.bukkit.event.player.PlayerDropItemEvent e) {
Player player = e.getPlayer();
TRNoDupe_BagCache cache;
if ((cache = TRNoDupe_BagCache.check(player)) != null) {
if (cache.hasBHBInBag) {
try {
TRNoDupe_BagCache.expire(cache);
e.setCancelled(true);
player.kickPlayer("[TRDupe] you have a Black Hole Band in your ["
+ cache.inBagColor
+ "] Alchemy Bag! Please remove it NOW!");
TRLogger.Log("Dupe", player.getName() + " ["
+ cache.inBagColor
+ " bag] attempted to dupe with the "
+ cache.dupeItem + "!");
TRLogger.broadcastDupe(player.getName(),
"the Alchemy Bag and " + cache.dupeItem, "alc");
} catch (Exception err) {
}
}
}
}
}
| true | true | public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
| public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
//tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
|
diff --git a/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java b/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java
index ea8f910b3..75c5698a0 100644
--- a/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java
+++ b/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java
@@ -1,288 +1,288 @@
package uk.ac.starlink.treeview;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.JComponent;
import nom.tam.fits.BasicHDU;
import nom.tam.fits.FitsException;
import nom.tam.fits.Header;
import uk.ac.starlink.array.AccessMode;
import uk.ac.starlink.array.BridgeNDArray;
import uk.ac.starlink.array.MouldArrayImpl;
import uk.ac.starlink.array.NDArray;
import uk.ac.starlink.array.NDShape;
import uk.ac.starlink.ast.AstException;
import uk.ac.starlink.ast.AstObject;
import uk.ac.starlink.ast.FitsChan;
import uk.ac.starlink.ast.Frame;
import uk.ac.starlink.ast.FrameSet;
import uk.ac.starlink.ast.SkyFrame;
import uk.ac.starlink.fits.FitsArrayBuilder;
import uk.ac.starlink.fits.MappedFile;
import uk.ac.starlink.splat.util.SplatException;
/**
* An implementation of the {@link DataNode} interface for
* representing Header and Data Units (HDUs) in FITS files.
*
* @author Mark Taylor (Starlink)
* @version $Id$
*/
public class ImageHDUDataNode extends HDUDataNode {
private Icon icon;
private String name;
private String description;
private String hduType;
private JComponent fullview;
private Header header;
private NDShape shape;
private final String dataType;
private String blank;
private BufferMaker bufmaker;
private Number badval;
private FrameSet wcs;
private String wcsEncoding;
/**
* Initialises an <code>ImageHDUDataNode</code> from a <code>Header</code>
* object.
*
* @param hdr a FITS header object
* from which the node is to be created.
* @param bufmaker an object capable of constructing the NIO buffer
* containing the header+data on demand
*/
public ImageHDUDataNode( Header hdr, BufferMaker bufmaker )
throws NoSuchDataException {
super( hdr );
this.header = hdr;
this.bufmaker = bufmaker;
hduType = getHduType();
if ( hduType != "Image" ) {
throw new NoSuchDataException( "Not an Image HDU" );
}
long[] axes = getDimsFromHeader( hdr );
int ndim = axes.length;
if ( axes != null && ndim > 0 ) {
shape = new NDShape( new long[ ndim ], axes );
}
boolean hasBlank = hdr.containsKey( "BLANK" );
badval = null;
blank = "<none>";
switch ( hdr.getIntValue( "BITPIX" ) ) {
case BasicHDU.BITPIX_BYTE:
dataType = "byte";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Byte( (byte) val );
}
break;
case BasicHDU.BITPIX_SHORT:
dataType = "short";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Short( (short) val );
}
break;
case BasicHDU.BITPIX_INT:
dataType = "int";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Integer( val );
}
break;
case BasicHDU.BITPIX_FLOAT:
dataType = "float";
blank = null;
break;
case BasicHDU.BITPIX_DOUBLE:
dataType = "double";
blank = null;
break;
case BasicHDU.BITPIX_LONG:
throw new NoSuchDataException(
"64-bit integers not supported by FITS" );
default:
dataType = null;
}
if ( Driver.hasAST ) {
try {
final Iterator hdrIt = hdr.iterator();
Iterator lineIt = new Iterator() {
public boolean hasNext() {
return hdrIt.hasNext();
}
public Object next() {
return hdrIt.next().toString();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
FitsChan chan = new FitsChan( lineIt );
wcsEncoding = chan.getEncoding();
AstObject aobj = chan.read();
if ( aobj != null && aobj instanceof FrameSet ) {
wcs = (FrameSet) aobj;
}
else {
wcsEncoding = null;
wcs = null;
}
}
catch ( AstException e ) {
wcsEncoding = null;
wcs = null;
}
}
else {
wcsEncoding = null;
wcs = null;
}
description = "(" + hduType
+ ( ( shape != null )
- ? ( " " + shape.toString() + " " )
+ ? ( " " + NDShape.toString( shape.getDims() ) + " " )
: "" )
+ ")";
}
public boolean allowsChildren() {
// return false;
return wcs != null;
}
public DataNode[] getChildren() {
if ( wcs == null ) {
// if ( true ) {
return new DataNode[ 0 ];
}
else {
DataNode wcschild;
try {
wcschild = new WCSDataNode( wcs );
}
catch ( NoSuchDataException e ) {
wcschild = new ErrorDataNode( e );
}
return new DataNode[] { wcschild };
}
}
public Icon getIcon() {
if ( icon == null ) {
if ( shape != null ) {
icon = IconFactory.getInstance()
.getArrayIcon( shape.getNumDims() );
}
else {
icon = IconFactory.getInstance()
.getIcon( IconFactory.HDU );
}
}
return icon;
}
public boolean hasFullView() {
return true;
}
public JComponent getFullView() {
if ( fullview == null ) {
DetailViewer dv = new DetailViewer( this );
fullview = dv.getComponent();
dv.addSeparator();
dv.addKeyedItem( "HDU type", hduType );
if ( shape != null ) {
dv.addKeyedItem( "Shape", shape );
}
if ( dataType != null ) {
dv.addKeyedItem( "Pixel type", dataType );
}
if ( blank != null ) {
dv.addKeyedItem( "Blank value", blank );
}
dv.addKeyedItem( "Number of header cards",
header.getNumberOfCards() );
if ( wcs != null ) {
dv.addSubHead( "World coordinate system" );
dv.addKeyedItem( "Encoding", wcsEncoding );
uk.ac.starlink.ast.Frame frm =
wcs.getFrame( FrameSet.AST__CURRENT );
dv.addKeyedItem( "Naxes", frm.getNaxes() );
if ( frm instanceof SkyFrame ) {
SkyFrame sfrm = (SkyFrame) frm;
dv.addKeyedItem( "Epoch", sfrm.getEpoch() );
dv.addKeyedItem( "Equinox", sfrm.getEquinox() );
dv.addKeyedItem( "Projection", sfrm.getProjection() );
dv.addKeyedItem( "System", sfrm.getSystem() );
}
}
dv.addPane( "Header cards", new ComponentMaker() {
public JComponent getComponent() {
return new TextViewer( header.iterator() );
}
} );
if ( shape != null && bufmaker != null ) {
try {
ByteBuffer bbuf = bufmaker.makeBuffer();
MappedFile mf = new MappedFile( bbuf );
NDArray nda = FitsArrayBuilder.getInstance()
.makeNDArray( mf, AccessMode.READ );
if ( ! nda.getShape().equals( shape ) ) {
nda = new BridgeNDArray(
new MouldArrayImpl( nda, shape ) );
}
NDArrayDataNode.addDataViews( dv, nda, wcs );
}
catch ( IOException e ) {
dv.logError( e );
}
}
}
return fullview;
}
public String getDescription() {
return description;
}
public String getNodeTLA() {
return "IMG";
}
public String getNodeType() {
return "FITS Image HDU";
}
private static long[] getDimsFromHeader( Header hdr ) {
try {
int naxis = hdr.getIntValue( "NAXIS" );
long[] dimensions = new long[ naxis ];
for ( int i = 0; i < naxis; i++ ) {
String key = "NAXIS" + ( i + 1 );
if ( hdr.containsKey( key ) ) {
dimensions[ i ] = hdr.getLongValue( key );
}
else {
throw new FitsException( "No header card + " + key );
}
}
return dimensions;
}
catch ( Exception e ) {
return null;
}
}
}
| true | true | public ImageHDUDataNode( Header hdr, BufferMaker bufmaker )
throws NoSuchDataException {
super( hdr );
this.header = hdr;
this.bufmaker = bufmaker;
hduType = getHduType();
if ( hduType != "Image" ) {
throw new NoSuchDataException( "Not an Image HDU" );
}
long[] axes = getDimsFromHeader( hdr );
int ndim = axes.length;
if ( axes != null && ndim > 0 ) {
shape = new NDShape( new long[ ndim ], axes );
}
boolean hasBlank = hdr.containsKey( "BLANK" );
badval = null;
blank = "<none>";
switch ( hdr.getIntValue( "BITPIX" ) ) {
case BasicHDU.BITPIX_BYTE:
dataType = "byte";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Byte( (byte) val );
}
break;
case BasicHDU.BITPIX_SHORT:
dataType = "short";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Short( (short) val );
}
break;
case BasicHDU.BITPIX_INT:
dataType = "int";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Integer( val );
}
break;
case BasicHDU.BITPIX_FLOAT:
dataType = "float";
blank = null;
break;
case BasicHDU.BITPIX_DOUBLE:
dataType = "double";
blank = null;
break;
case BasicHDU.BITPIX_LONG:
throw new NoSuchDataException(
"64-bit integers not supported by FITS" );
default:
dataType = null;
}
if ( Driver.hasAST ) {
try {
final Iterator hdrIt = hdr.iterator();
Iterator lineIt = new Iterator() {
public boolean hasNext() {
return hdrIt.hasNext();
}
public Object next() {
return hdrIt.next().toString();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
FitsChan chan = new FitsChan( lineIt );
wcsEncoding = chan.getEncoding();
AstObject aobj = chan.read();
if ( aobj != null && aobj instanceof FrameSet ) {
wcs = (FrameSet) aobj;
}
else {
wcsEncoding = null;
wcs = null;
}
}
catch ( AstException e ) {
wcsEncoding = null;
wcs = null;
}
}
else {
wcsEncoding = null;
wcs = null;
}
description = "(" + hduType
+ ( ( shape != null )
? ( " " + shape.toString() + " " )
: "" )
+ ")";
}
| public ImageHDUDataNode( Header hdr, BufferMaker bufmaker )
throws NoSuchDataException {
super( hdr );
this.header = hdr;
this.bufmaker = bufmaker;
hduType = getHduType();
if ( hduType != "Image" ) {
throw new NoSuchDataException( "Not an Image HDU" );
}
long[] axes = getDimsFromHeader( hdr );
int ndim = axes.length;
if ( axes != null && ndim > 0 ) {
shape = new NDShape( new long[ ndim ], axes );
}
boolean hasBlank = hdr.containsKey( "BLANK" );
badval = null;
blank = "<none>";
switch ( hdr.getIntValue( "BITPIX" ) ) {
case BasicHDU.BITPIX_BYTE:
dataType = "byte";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Byte( (byte) val );
}
break;
case BasicHDU.BITPIX_SHORT:
dataType = "short";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Short( (short) val );
}
break;
case BasicHDU.BITPIX_INT:
dataType = "int";
if ( hasBlank ) {
int val = hdr.getIntValue( "BLANK" );
blank = "" + val;
badval = new Integer( val );
}
break;
case BasicHDU.BITPIX_FLOAT:
dataType = "float";
blank = null;
break;
case BasicHDU.BITPIX_DOUBLE:
dataType = "double";
blank = null;
break;
case BasicHDU.BITPIX_LONG:
throw new NoSuchDataException(
"64-bit integers not supported by FITS" );
default:
dataType = null;
}
if ( Driver.hasAST ) {
try {
final Iterator hdrIt = hdr.iterator();
Iterator lineIt = new Iterator() {
public boolean hasNext() {
return hdrIt.hasNext();
}
public Object next() {
return hdrIt.next().toString();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
FitsChan chan = new FitsChan( lineIt );
wcsEncoding = chan.getEncoding();
AstObject aobj = chan.read();
if ( aobj != null && aobj instanceof FrameSet ) {
wcs = (FrameSet) aobj;
}
else {
wcsEncoding = null;
wcs = null;
}
}
catch ( AstException e ) {
wcsEncoding = null;
wcs = null;
}
}
else {
wcsEncoding = null;
wcs = null;
}
description = "(" + hduType
+ ( ( shape != null )
? ( " " + NDShape.toString( shape.getDims() ) + " " )
: "" )
+ ")";
}
|
diff --git a/src/main/java/net/minecraft/src/RenderItem.java b/src/main/java/net/minecraft/src/RenderItem.java
index 0ec477d5..e98523c2 100644
--- a/src/main/java/net/minecraft/src/RenderItem.java
+++ b/src/main/java/net/minecraft/src/RenderItem.java
@@ -1,547 +1,549 @@
package net.minecraft.src;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
// Spout Start
import org.newdawn.slick.opengl.Texture;
import org.spoutcraft.api.block.design.BlockDesign;
import org.spoutcraft.api.material.MaterialData;
import org.spoutcraft.client.io.CustomTextureManager;
// Spout End
public class RenderItem extends Render {
private RenderBlocks renderBlocks = new RenderBlocks();
/** The RNG used in RenderItem (for bobbing itemstacks on the ground) */
private Random random = new Random();
public boolean field_77024_a = true;
/** Defines the zLevel of rendering of item on GUI. */
public float zLevel = 0.0F;
public static boolean field_82407_g = false;
public RenderItem() {
this.shadowSize = 0.15F;
this.shadowOpaque = 0.75F;
}
// Spout Start
@Override
protected void loadTexture(String texture) {
if (this.renderManager != null && this.renderManager.renderEngine != null) {
int textureId = this.renderManager.renderEngine.getTexture(texture);
if (textureId >= 0) {
this.renderManager.renderEngine.bindTexture(textureId);
}
}
}
// Spout End
/**
* Renders the item
*/
public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) {
// Spout Start
// Sanity Checks
if (par1EntityItem == null || par1EntityItem.item == null) {
return;
}
// Spout End
this.random.setSeed(187L);
ItemStack var10 = par1EntityItem.item;
if (var10.getItem() != null) {
// GL11.glPushMatrix(); // Spout delate to later, if no custom design given
float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F;
float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI);
byte var13 = 1;
if (par1EntityItem.item.stackSize > 1) {
var13 = 2;
}
if (par1EntityItem.item.stackSize > 5) {
var13 = 3;
}
if (par1EntityItem.item.stackSize > 20) {
var13 = 4;
}
// Spout Start
boolean custom = false;
BlockDesign design = null;
if (var10.itemID == 318) {
org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage());
if (item != null) {
String textureURI = item.getTexture();
if (textureURI == null) {
org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage());
design = block != null ? block.getBlockDesign() : null;
textureURI = design != null ? design.getTexureURL() : null;
}
if (textureURI != null) {
Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI);
if (texture != null) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
custom = true;
}
}
}
/*
* org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null &&
* design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if
* (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } }
*/
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
if (design != null && custom) {
//GL11.glScalef(0.25F, 0.25F, 0.25F);
design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random);
} else {
GL11.glPushMatrix(); // the push from above
if (!custom) {
if (var10.itemID < 256) {
this.loadTexture("/terrain.png");
} else {
this.loadTexture("/gui/items.png");
}
}
// Spout End
GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
Block var14 = Block.blocksList[var10.itemID];
int var16;
float var19;
float var20;
float var24;
if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) {
GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F);
if (field_82407_g) {
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
this.loadTexture("/terrain.png");
float var22 = 0.25F;
var16 = var14.getRenderType();
if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) {
var22 = 0.5F;
}
GL11.glScalef(var22, var22, var22);
for (int var23 = 0; var23 < var13; ++var23) {
GL11.glPushMatrix();
if (var23 > 0) {
var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
GL11.glTranslatef(var24, var19, var20);
}
var24 = 1.0F;
this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24);
GL11.glPopMatrix();
}
} else {
int var15;
float var17;
if (var10.getItem().requiresMultipleRenderPasses()) {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
this.loadTexture("/gui/items.png");
for (var15 = 0; var15 <= 1; ++var15) {
var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15);
var17 = 1.0F;
if (this.field_77024_a) {
int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15);
var19 = (float)(var18 >> 16 & 255) / 255.0F;
var20 = (float)(var18 >> 8 & 255) / 255.0F;
float var21 = (float)(var18 & 255) / 255.0F;
GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F);
}
this.func_77020_a(var16, var13);
}
} else {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
var15 = var10.getIconIndex();
if (var14 != null) {
this.loadTexture("/terrain.png");
} else {
- this.loadTexture("/gui/items.png");
+ if (!custom) {
+ this.loadTexture("/gui/items.png");
+ }
}
if (this.field_77024_a) {
var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0);
var17 = (float)(var16 >> 16 & 255) / 255.0F;
var24 = (float)(var16 >> 8 & 255) / 255.0F;
var19 = (float)(var16 & 255) / 255.0F;
var20 = 1.0F;
GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F);
}
// Spout Start
this.renderItemBillboard(var15, var13, custom);
// Spout End
}
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
} // Spout
}
}
// Spout Start
private void func_77020_a(int var1, int var2) {
renderItemBillboard(var1, var2, false);
}
private void renderItemBillboard(int par1, int par2, boolean customTexture) {
// Spout End
Tessellator var3 = Tessellator.instance;
float var4 = (float)(par1 % 16 * 16 + 0) / 256.0F;
float var5 = (float)(par1 % 16 * 16 + 16) / 256.0F;
float var6 = (float)(par1 / 16 * 16 + 0) / 256.0F;
float var7 = (float)(par1 / 16 * 16 + 16) / 256.0F;
float var8 = 1.0F;
float var9 = 0.5F;
float var10 = 0.25F;
// Spout Start
if (customTexture) {
var4 = 0F;
var5 = 1F;
var6 = 1F;
var7 = 0F;
}
// Spout End
for (int var11 = 0; var11 < par2; ++var11) {
GL11.glPushMatrix();
if (var11 > 0) {
float var12 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
float var13 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
float var14 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F;
GL11.glTranslatef(var12, var13, var14);
}
GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
var3.startDrawingQuads();
var3.setNormal(0.0F, 1.0F, 0.0F);
var3.addVertexWithUV((double)(0.0F - var9), (double)(0.0F - var10), 0.0D, (double)var4, (double)var7);
var3.addVertexWithUV((double)(var8 - var9), (double)(0.0F - var10), 0.0D, (double)var5, (double)var7);
var3.addVertexWithUV((double)(var8 - var9), (double)(1.0F - var10), 0.0D, (double)var5, (double)var6);
var3.addVertexWithUV((double)(0.0F - var9), (double)(1.0F - var10), 0.0D, (double)var4, (double)var6);
var3.draw();
GL11.glPopMatrix();
}
}
/**
* Renders the item's icon or block into the UI at the specified position.
*/
public void renderItemIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) {
int var6 = par3ItemStack.itemID;
int var7 = par3ItemStack.getItemDamage();
int var8 = par3ItemStack.getIconIndex();
int var10;
float var12;
float var13;
float var16;
// Spout Start
boolean custom = false;
BlockDesign design = null;
if (var6 == 318) {
org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var7);
if (item != null) {
String textureURI = item.getTexture();
if (textureURI == null) {
org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var7);
design = block != null ? block.getBlockDesign() : null;
textureURI = design != null ? design.getTexureURL() : null;
}
if (textureURI != null) {
Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI);
if (texture != null) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
custom = true;
}
}
}
}
if (!custom) {
if (var6 < 256) {
loadTexture("/terrain.png");
} else {
loadTexture("/gui/items.png");
}
}
if (design != null && custom) {
design.renderItemOnHUD((float)(par4 - 2), (float)(par5 + 3), -3.0F + this.zLevel);
} else if (var6 < 256 && RenderBlocks.renderItemIn3d(Block.blocksList[var6].getRenderType())) {
// Spout End
par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/terrain.png"));
Block var15 = Block.blocksList[var6];
GL11.glPushMatrix();
GL11.glTranslatef((float)(par4 - 2), (float)(par5 + 3), -3.0F + this.zLevel);
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F, 1.0F, -1.0F);
GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
var10 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, 0);
var16 = (float)(var10 >> 16 & 255) / 255.0F;
var12 = (float)(var10 >> 8 & 255) / 255.0F;
var13 = (float)(var10 & 255) / 255.0F;
if (this.field_77024_a) {
GL11.glColor4f(var16, var12, var13, 1.0F);
}
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
this.renderBlocks.useInventoryTint = this.field_77024_a;
this.renderBlocks.renderBlockAsItem(var15, var7, 1.0F);
this.renderBlocks.useInventoryTint = true;
GL11.glPopMatrix();
} else {
int var9;
if (Item.itemsList[var6].requiresMultipleRenderPasses()) {
GL11.glDisable(GL11.GL_LIGHTING);
par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/gui/items.png"));
for (var9 = 0; var9 <= 1; ++var9) {
var10 = Item.itemsList[var6].getIconFromDamageForRenderPass(var7, var9);
int var11 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, var9);
var12 = (float)(var11 >> 16 & 255) / 255.0F;
var13 = (float)(var11 >> 8 & 255) / 255.0F;
float var14 = (float)(var11 & 255) / 255.0F;
if (this.field_77024_a) {
GL11.glColor4f(var12, var13, var14, 1.0F);
}
this.renderTexturedQuad(par4, par5, var10 % 16 * 16, var10 / 16 * 16, 16, 16);
}
GL11.glEnable(GL11.GL_LIGHTING);
} else if (var8 >= 0) {
GL11.glDisable(GL11.GL_LIGHTING);
if (var6 < 256) {
par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/terrain.png"));
} else {
par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/gui/items.png"));
}
var9 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, 0);
float var17 = (float)(var9 >> 16 & 255) / 255.0F;
var16 = (float)(var9 >> 8 & 255) / 255.0F;
var12 = (float)(var9 & 255) / 255.0F;
if (this.field_77024_a) {
GL11.glColor4f(var17, var16, var12, 1.0F);
}
// Spout Start
if (custom) {
Tessellator tes = Tessellator.instance;
tes.startDrawingQuads();
tes.addVertexWithUV((double)(par4 + 0), (double)(par5 + 16), (double)0, 0, 0);
tes.addVertexWithUV((double)(par4 + 16), (double)(par5 + 16), (double)0, 1, 0);
tes.addVertexWithUV((double)(par4 + 16), (double)(par5 + 0), (double)0, 1, 1);
tes.addVertexWithUV((double)(par4 + 0), (double)(par5 + 0), (double)0, 0, 1);
tes.draw();
} else
this.renderTexturedQuad(par4, par5, var8 % 16 * 16, var8 / 16 * 16, 16, 16);
// Spout End
GL11.glEnable(GL11.GL_LIGHTING);
}
}
GL11.glEnable(GL11.GL_CULL_FACE);
}
/**
* Render the item's icon or block into the GUI, including the glint effect.
*/
public void renderItemAndEffectIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) {
if (par3ItemStack != null) {
this.renderItemIntoGUI(par1FontRenderer, par2RenderEngine, par3ItemStack, par4, par5);
if (par3ItemStack != null && par3ItemStack.hasEffect()) {
GL11.glDepthFunc(GL11.GL_GREATER);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
par2RenderEngine.bindTexture(par2RenderEngine.getTexture("%blur%/misc/glint.png"));
this.zLevel -= 50.0F;
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR);
GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F);
this.func_77018_a(par4 * 431278612 + par5 * 32178161, par4 - 2, par5 - 2, 20, 20);
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
this.zLevel += 50.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
}
}
private void func_77018_a(int par1, int par2, int par3, int par4, int par5) {
for (int var6 = 0; var6 < 2; ++var6) {
if (var6 == 0) {
GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
}
if (var6 == 1) {
GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);
}
float var7 = 0.00390625F;
float var8 = 0.00390625F;
float var9 = (float)(Minecraft.getSystemTime() % (long)(3000 + var6 * 1873)) / (3000.0F + (float)(var6 * 1873)) * 256.0F;
float var10 = 0.0F;
Tessellator var11 = Tessellator.instance;
float var12 = 4.0F;
if (var6 == 1) {
var12 = -1.0F;
}
var11.startDrawingQuads();
var11.addVertexWithUV((double)(par2 + 0), (double)(par3 + par5), (double)this.zLevel, (double)((var9 + (float)par5 * var12) * var7), (double)((var10 + (float)par5) * var8));
var11.addVertexWithUV((double)(par2 + par4), (double)(par3 + par5), (double)this.zLevel, (double)((var9 + (float)par4 + (float)par5 * var12) * var7), (double)((var10 + (float)par5) * var8));
var11.addVertexWithUV((double)(par2 + par4), (double)(par3 + 0), (double)this.zLevel, (double)((var9 + (float)par4) * var7), (double)((var10 + 0.0F) * var8));
var11.addVertexWithUV((double)(par2 + 0), (double)(par3 + 0), (double)this.zLevel, (double)((var9 + 0.0F) * var7), (double)((var10 + 0.0F) * var8));
var11.draw();
}
}
/**
* Renders the item's overlay information. Examples being stack count or damage on top of the item's image at the
* specified position.
*/
public void renderItemOverlayIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) {
if (par3ItemStack != null) {
if (par3ItemStack.stackSize > 1) {
String var6 = "" + par3ItemStack.stackSize;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
par1FontRenderer.drawStringWithShadow(var6, par4 + 19 - 2 - par1FontRenderer.getStringWidth(var6), par5 + 6 + 3, 16777215);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
// Spout Start
NBTTagList list = par3ItemStack.getAllEnchantmentTagList();
short max = -1;
short amnt = -1;
if (list != null) {
for (int i = 0; i < list.tagCount(); i++) {
NBTBase tag = list.tagAt(i);
if (tag instanceof NBTTagCompound) {
NBTTagCompound ench = (NBTTagCompound)tag;
short id = ench.getShort("id");
short lvl = ench.getShort("lvl");
if (id == 254)
amnt = lvl; //Enchantment DURABILITY = new SpoutEnchantment(254);
if (id == 255)
max = lvl; //Enchantment MAX_DURABILITY = new SpoutEnchantment(255);
}
}
}
boolean override = max > 0 && amnt > 0 && amnt < max;
if (par3ItemStack.isItemDamaged() || override) {
int var11 = (int)Math.round(13.0D - (double)(override ? amnt : par3ItemStack.getItemDamageForDisplay()) * 13.0D / (double)(override ? max : par3ItemStack.getMaxDamage()));
int var7 = (int)Math.round(255.0D - (double)(override ? amnt : par3ItemStack.getItemDamageForDisplay()) * 255.0D / (double)(override ? max : par3ItemStack.getMaxDamage()));
// Spout End
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
Tessellator var8 = Tessellator.instance;
int var9 = 255 - var7 << 16 | var7 << 8;
int var10 = (255 - var7) / 4 << 16 | 16128;
this.renderQuad(var8, par4 + 2, par5 + 13, 13, 2, 0);
this.renderQuad(var8, par4 + 2, par5 + 13, 12, 1, var10);
this.renderQuad(var8, par4 + 2, par5 + 13, var11, 1, var9);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
}
}
/**
* Adds a quad to the tesselator at the specified position with the set width and height and color. Args: tessellator,
* x, y, width, height, color
*/
private void renderQuad(Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6) {
par1Tessellator.startDrawingQuads();
par1Tessellator.setColorOpaque_I(par6);
par1Tessellator.addVertex((double)(par2 + 0), (double)(par3 + 0), 0.0D);
par1Tessellator.addVertex((double)(par2 + 0), (double)(par3 + par5), 0.0D);
par1Tessellator.addVertex((double)(par2 + par4), (double)(par3 + par5), 0.0D);
par1Tessellator.addVertex((double)(par2 + par4), (double)(par3 + 0), 0.0D);
par1Tessellator.draw();
}
/**
* Adds a textured quad to the tesselator at the specified position with the specified texture coords, width and
* height. Args: x, y, u, v, width, height
*/
public void renderTexturedQuad(int par1, int par2, int par3, int par4, int par5, int par6) {
float var7 = 0.00390625F;
float var8 = 0.00390625F;
Tessellator var9 = Tessellator.instance;
var9.startDrawingQuads();
var9.addVertexWithUV((double)(par1 + 0), (double)(par2 + par6), (double)this.zLevel, (double)((float)(par3 + 0) * var7), (double)((float)(par4 + par6) * var8));
var9.addVertexWithUV((double)(par1 + par5), (double)(par2 + par6), (double)this.zLevel, (double)((float)(par3 + par5) * var7), (double)((float)(par4 + par6) * var8));
var9.addVertexWithUV((double)(par1 + par5), (double)(par2 + 0), (double)this.zLevel, (double)((float)(par3 + par5) * var7), (double)((float)(par4 + 0) * var8));
var9.addVertexWithUV((double)(par1 + 0), (double)(par2 + 0), (double)this.zLevel, (double)((float)(par3 + 0) * var7), (double)((float)(par4 + 0) * var8));
var9.draw();
}
/**
* Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
* handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
* (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1,
* double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
*/
public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) {
this.doRenderItem((EntityItem)par1Entity, par2, par4, par6, par8, par9);
}
}
| true | true | public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) {
// Spout Start
// Sanity Checks
if (par1EntityItem == null || par1EntityItem.item == null) {
return;
}
// Spout End
this.random.setSeed(187L);
ItemStack var10 = par1EntityItem.item;
if (var10.getItem() != null) {
// GL11.glPushMatrix(); // Spout delate to later, if no custom design given
float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F;
float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI);
byte var13 = 1;
if (par1EntityItem.item.stackSize > 1) {
var13 = 2;
}
if (par1EntityItem.item.stackSize > 5) {
var13 = 3;
}
if (par1EntityItem.item.stackSize > 20) {
var13 = 4;
}
// Spout Start
boolean custom = false;
BlockDesign design = null;
if (var10.itemID == 318) {
org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage());
if (item != null) {
String textureURI = item.getTexture();
if (textureURI == null) {
org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage());
design = block != null ? block.getBlockDesign() : null;
textureURI = design != null ? design.getTexureURL() : null;
}
if (textureURI != null) {
Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI);
if (texture != null) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
custom = true;
}
}
}
/*
* org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null &&
* design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if
* (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } }
*/
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
if (design != null && custom) {
//GL11.glScalef(0.25F, 0.25F, 0.25F);
design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random);
} else {
GL11.glPushMatrix(); // the push from above
if (!custom) {
if (var10.itemID < 256) {
this.loadTexture("/terrain.png");
} else {
this.loadTexture("/gui/items.png");
}
}
// Spout End
GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
Block var14 = Block.blocksList[var10.itemID];
int var16;
float var19;
float var20;
float var24;
if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) {
GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F);
if (field_82407_g) {
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
this.loadTexture("/terrain.png");
float var22 = 0.25F;
var16 = var14.getRenderType();
if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) {
var22 = 0.5F;
}
GL11.glScalef(var22, var22, var22);
for (int var23 = 0; var23 < var13; ++var23) {
GL11.glPushMatrix();
if (var23 > 0) {
var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
GL11.glTranslatef(var24, var19, var20);
}
var24 = 1.0F;
this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24);
GL11.glPopMatrix();
}
} else {
int var15;
float var17;
if (var10.getItem().requiresMultipleRenderPasses()) {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
this.loadTexture("/gui/items.png");
for (var15 = 0; var15 <= 1; ++var15) {
var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15);
var17 = 1.0F;
if (this.field_77024_a) {
int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15);
var19 = (float)(var18 >> 16 & 255) / 255.0F;
var20 = (float)(var18 >> 8 & 255) / 255.0F;
float var21 = (float)(var18 & 255) / 255.0F;
GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F);
}
this.func_77020_a(var16, var13);
}
} else {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
var15 = var10.getIconIndex();
if (var14 != null) {
this.loadTexture("/terrain.png");
} else {
this.loadTexture("/gui/items.png");
}
if (this.field_77024_a) {
var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0);
var17 = (float)(var16 >> 16 & 255) / 255.0F;
var24 = (float)(var16 >> 8 & 255) / 255.0F;
var19 = (float)(var16 & 255) / 255.0F;
var20 = 1.0F;
GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F);
}
// Spout Start
this.renderItemBillboard(var15, var13, custom);
// Spout End
}
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
} // Spout
}
}
| public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) {
// Spout Start
// Sanity Checks
if (par1EntityItem == null || par1EntityItem.item == null) {
return;
}
// Spout End
this.random.setSeed(187L);
ItemStack var10 = par1EntityItem.item;
if (var10.getItem() != null) {
// GL11.glPushMatrix(); // Spout delate to later, if no custom design given
float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F;
float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI);
byte var13 = 1;
if (par1EntityItem.item.stackSize > 1) {
var13 = 2;
}
if (par1EntityItem.item.stackSize > 5) {
var13 = 3;
}
if (par1EntityItem.item.stackSize > 20) {
var13 = 4;
}
// Spout Start
boolean custom = false;
BlockDesign design = null;
if (var10.itemID == 318) {
org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage());
if (item != null) {
String textureURI = item.getTexture();
if (textureURI == null) {
org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage());
design = block != null ? block.getBlockDesign() : null;
textureURI = design != null ? design.getTexureURL() : null;
}
if (textureURI != null) {
Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI);
if (texture != null) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
custom = true;
}
}
}
/*
* org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null &&
* design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if
* (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } }
*/
}
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
if (design != null && custom) {
//GL11.glScalef(0.25F, 0.25F, 0.25F);
design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random);
} else {
GL11.glPushMatrix(); // the push from above
if (!custom) {
if (var10.itemID < 256) {
this.loadTexture("/terrain.png");
} else {
this.loadTexture("/gui/items.png");
}
}
// Spout End
GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
Block var14 = Block.blocksList[var10.itemID];
int var16;
float var19;
float var20;
float var24;
if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) {
GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F);
if (field_82407_g) {
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
this.loadTexture("/terrain.png");
float var22 = 0.25F;
var16 = var14.getRenderType();
if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) {
var22 = 0.5F;
}
GL11.glScalef(var22, var22, var22);
for (int var23 = 0; var23 < var13; ++var23) {
GL11.glPushMatrix();
if (var23 > 0) {
var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22;
GL11.glTranslatef(var24, var19, var20);
}
var24 = 1.0F;
this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24);
GL11.glPopMatrix();
}
} else {
int var15;
float var17;
if (var10.getItem().requiresMultipleRenderPasses()) {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
this.loadTexture("/gui/items.png");
for (var15 = 0; var15 <= 1; ++var15) {
var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15);
var17 = 1.0F;
if (this.field_77024_a) {
int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15);
var19 = (float)(var18 >> 16 & 255) / 255.0F;
var20 = (float)(var18 >> 8 & 255) / 255.0F;
float var21 = (float)(var18 & 255) / 255.0F;
GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F);
}
this.func_77020_a(var16, var13);
}
} else {
if (field_82407_g) {
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
GL11.glDisable(GL11.GL_LIGHTING);
} else {
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
var15 = var10.getIconIndex();
if (var14 != null) {
this.loadTexture("/terrain.png");
} else {
if (!custom) {
this.loadTexture("/gui/items.png");
}
}
if (this.field_77024_a) {
var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0);
var17 = (float)(var16 >> 16 & 255) / 255.0F;
var24 = (float)(var16 >> 8 & 255) / 255.0F;
var19 = (float)(var16 & 255) / 255.0F;
var20 = 1.0F;
GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F);
}
// Spout Start
this.renderItemBillboard(var15, var13, custom);
// Spout End
}
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
} // Spout
}
}
|
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java
index 78461e4..2d51be4 100644
--- a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java
@@ -1,612 +1,616 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* RAM File Random Access Content.
* @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a>
*/
public class RamFileRandomAccessContent implements RandomAccessContent
{
/**
* File Pointer
*/
protected int filePointer = 0;
/**
* Buffer
*/
private byte[] buf;
/**
* buffer
*/
private final byte[] buffer8 = new byte[8];
/**
* buffer
*/
private final byte[] buffer4 = new byte[4];
/**
* buffer
*/
private final byte[] buffer2 = new byte[2];
/**
* buffer
*/
private final byte[] buffer1 = new byte[1];
/**
* Mode
*/
private final RandomAccessMode mode;
/**
* File
*/
private final RamFileObject file;
private final InputStream rafis;
/**
* @param file The file to access.
* @param mode The access mode.
*/
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode)
{
super();
this.buf = file.getData().getBuffer();
this.file = file;
this.mode = mode;
rafis = new InputStream()
{
@Override
public int read() throws IOException
{
try
{
return readByte();
}
catch (EOFException e)
{
return -1;
}
}
@Override
public long skip(long n) throws IOException
{
seek(getFilePointer() + n);
return n;
}
@Override
public void close() throws IOException
{
}
@Override
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
- int retLen = Math.min(len, getLeftBytes());
- RamFileRandomAccessContent.this.readFully(b, off, retLen);
+ int retLen = -1;
+ final int left = getLeftBytes();
+ if (left > 0) {
+ retLen = Math.min(len, left);
+ RamFileRandomAccessContent.this.readFully(b, off, retLen);
+ }
return retLen;
}
@Override
public int available() throws IOException
{
return getLeftBytes();
}
};
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer()
*/
public long getFilePointer() throws IOException
{
return this.filePointer;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#seek(long)
*/
public void seek(long pos) throws IOException
{
if (pos < 0) {
throw new IOException("Attempt to position before the start of the file");
}
this.filePointer = (int) pos;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#length()
*/
public long length() throws IOException
{
return buf.length;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#close()
*/
public void close() throws IOException
{
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readByte()
*/
public byte readByte() throws IOException
{
return (byte) this.readUnsignedByte();
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readChar()
*/
public char readChar() throws IOException
{
int ch1 = this.readUnsignedByte();
int ch2 = this.readUnsignedByte();
return (char) ((ch1 << 8) + (ch2 << 0));
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readDouble()
*/
public double readDouble() throws IOException
{
return Double.longBitsToDouble(this.readLong());
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFloat()
*/
public float readFloat() throws IOException
{
return Float.intBitsToFloat(this.readInt());
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readInt()
*/
public int readInt() throws IOException
{
return (readUnsignedByte() << 24) | (readUnsignedByte() << 16)
| (readUnsignedByte() << 8) | readUnsignedByte();
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUnsignedByte()
*/
public int readUnsignedByte() throws IOException
{
if (filePointer < buf.length)
{
return buf[filePointer++] & 0xFF;
}
else
{
throw new EOFException();
}
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUnsignedShort()
*/
public int readUnsignedShort() throws IOException
{
this.readFully(buffer2);
return toUnsignedShort(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readLong()
*/
public long readLong() throws IOException
{
this.readFully(buffer8);
return toLong(buffer8);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readShort()
*/
public short readShort() throws IOException
{
this.readFully(buffer2);
return toShort(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readBoolean()
*/
public boolean readBoolean() throws IOException
{
return (this.readUnsignedByte() != 0);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#skipBytes(int)
*/
public int skipBytes(int n) throws IOException
{
if (n < 0)
{
throw new IndexOutOfBoundsException(
"The skip number can't be negative");
}
long newPos = filePointer + n;
if (newPos > buf.length)
{
throw new IndexOutOfBoundsException("Tyring to skip too much bytes");
}
seek(newPos);
return n;
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFully(byte[])
*/
public void readFully(byte[] b) throws IOException
{
this.readFully(b, 0, b.length);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFully(byte[], int, int)
*/
public void readFully(byte[] b, int off, int len) throws IOException
{
if (len < 0)
{
throw new IndexOutOfBoundsException("Length is lower than 0");
}
if (len > this.getLeftBytes())
{
throw new IndexOutOfBoundsException("Read length (" + len
+ ") is higher than buffer left bytes ("
+ this.getLeftBytes() + ") ");
}
System.arraycopy(buf, filePointer, b, off, len);
filePointer += len;
}
private int getLeftBytes()
{
return buf.length - filePointer;
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUTF()
*/
public String readUTF() throws IOException
{
return DataInputStream.readUTF(this);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(byte[], int, int)
*/
public void write(byte[] b, int off, int len) throws IOException
{
if (this.getLeftBytes() < len)
{
int newSize = this.buf.length + len - this.getLeftBytes();
this.file.resize(newSize);
this.buf = this.file.getData().getBuffer();
}
System.arraycopy(b, off, this.buf, filePointer, len);
this.filePointer += len;
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(byte[])
*/
public void write(byte[] b) throws IOException
{
this.write(b, 0, b.length);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeByte(int)
*/
public void writeByte(int i) throws IOException
{
this.write(i);
}
/**
* Build a long from first 8 bytes of the array.
*
* @param b The byte[] to convert.
* @return A long.
*/
public static long toLong(byte[] b)
{
return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8)
+ ((((long) b[5]) & 0xFF) << 16)
+ ((((long) b[4]) & 0xFF) << 24)
+ ((((long) b[3]) & 0xFF) << 32)
+ ((((long) b[2]) & 0xFF) << 40)
+ ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56));
}
/**
* Build a 8-byte array from a long. No check is performed on the array
* length.
*
* @param n The number to convert.
* @param b The array to fill.
* @return A byte[].
*/
public static byte[] toBytes(long n, byte[] b)
{
b[7] = (byte) (n);
n >>>= 8;
b[6] = (byte) (n);
n >>>= 8;
b[5] = (byte) (n);
n >>>= 8;
b[4] = (byte) (n);
n >>>= 8;
b[3] = (byte) (n);
n >>>= 8;
b[2] = (byte) (n);
n >>>= 8;
b[1] = (byte) (n);
n >>>= 8;
b[0] = (byte) (n);
return b;
}
/**
* Build a short from first 2 bytes of the array.
* @param b The byte[] to convert.
* @return A short.
*/
public static short toShort(byte[] b)
{
return (short) toUnsignedShort(b);
}
/**
* Build a short from first 2 bytes of the array.
*
* @param b The byte[] to convert.
* @return A short.
*/
public static int toUnsignedShort(byte[] b)
{
return ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(int)
*/
public void write(int b) throws IOException
{
buffer1[0] = (byte) b;
this.write(buffer1);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeBoolean(boolean)
*/
public void writeBoolean(boolean v) throws IOException
{
this.write(v ? 1 : 0);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeBytes(java.lang.String)
*/
public void writeBytes(String s) throws IOException
{
write(s.getBytes());
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeChar(int)
*/
public void writeChar(int v) throws IOException
{
buffer2[0] = (byte) ((v >>> 8) & 0xFF);
buffer2[1] = (byte) ((v >>> 0) & 0xFF);
write(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeChars(java.lang.String)
*/
public void writeChars(String s) throws IOException
{
int len = s.length();
for (int i = 0; i < len; i++)
{
writeChar(s.charAt(i));
}
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeDouble(double)
*/
public void writeDouble(double v) throws IOException
{
writeLong(Double.doubleToLongBits(v));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeFloat(float)
*/
public void writeFloat(float v) throws IOException
{
writeInt(Float.floatToIntBits(v));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeInt(int)
*/
public void writeInt(int v) throws IOException
{
buffer4[0] = (byte) ((v >>> 24) & 0xFF);
buffer4[1] = (byte) ((v >>> 16) & 0xFF);
buffer4[2] = (byte) ((v >>> 8) & 0xFF);
buffer4[3] = (byte) (v & 0xFF);
write(buffer4);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeLong(long)
*/
public void writeLong(long v) throws IOException
{
write(toBytes(v, buffer8));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeShort(int)
*/
public void writeShort(int v) throws IOException
{
buffer2[0] = (byte) ((v >>> 8) & 0xFF);
buffer2[1] = (byte) (v & 0xFF);
write(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeUTF(java.lang.String)
*/
public void writeUTF(String str) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeUTF(str);
dataOut.flush();
dataOut.close();
byte[] b = out.toByteArray();
write(b);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readLine()
*/
public String readLine() throws IOException
{
throw new UnsupportedOperationException("deprecated");
}
public InputStream getInputStream() throws IOException
{
return rafis;
}
}
| true | true | public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode)
{
super();
this.buf = file.getData().getBuffer();
this.file = file;
this.mode = mode;
rafis = new InputStream()
{
@Override
public int read() throws IOException
{
try
{
return readByte();
}
catch (EOFException e)
{
return -1;
}
}
@Override
public long skip(long n) throws IOException
{
seek(getFilePointer() + n);
return n;
}
@Override
public void close() throws IOException
{
}
@Override
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int retLen = Math.min(len, getLeftBytes());
RamFileRandomAccessContent.this.readFully(b, off, retLen);
return retLen;
}
@Override
public int available() throws IOException
{
return getLeftBytes();
}
};
}
| public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode)
{
super();
this.buf = file.getData().getBuffer();
this.file = file;
this.mode = mode;
rafis = new InputStream()
{
@Override
public int read() throws IOException
{
try
{
return readByte();
}
catch (EOFException e)
{
return -1;
}
}
@Override
public long skip(long n) throws IOException
{
seek(getFilePointer() + n);
return n;
}
@Override
public void close() throws IOException
{
}
@Override
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int retLen = -1;
final int left = getLeftBytes();
if (left > 0) {
retLen = Math.min(len, left);
RamFileRandomAccessContent.this.readFully(b, off, retLen);
}
return retLen;
}
@Override
public int available() throws IOException
{
return getLeftBytes();
}
};
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/strategy/All.java b/src/org/meta_environment/rascal/interpreter/strategy/All.java
index 954781fedc..9e19614a1f 100644
--- a/src/org/meta_environment/rascal/interpreter/strategy/All.java
+++ b/src/org/meta_environment/rascal/interpreter/strategy/All.java
@@ -1,45 +1,45 @@
package org.meta_environment.rascal.interpreter.strategy;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.meta_environment.rascal.interpreter.IEvaluatorContext;
import org.meta_environment.rascal.interpreter.result.AbstractFunction;
import org.meta_environment.rascal.interpreter.result.ElementResult;
import org.meta_environment.rascal.interpreter.result.OverloadedFunctionResult;
import org.meta_environment.rascal.interpreter.result.Result;
public class All extends Strategy {
public All(AbstractFunction function) {
super(function);
}
@Override
public Result<?> call(Type[] argTypes, IValue[] argValues,
IEvaluatorContext ctx) {
Visitable result = VisitableFactory.make(argValues[0]);
for (int i = 0; i < result.arity(); i++) {
IValue child = result.get(i).getValue();
result = result.set(i, VisitableFactory.make(function.call(new Type[]{child.getType()}, new IValue[]{child}, ctx).getValue()));
}
return new ElementResult<IValue>(result.getValue().getType(), result.getValue(), ctx);
}
public static IValue makeAll(IValue arg) {
if (arg instanceof AbstractFunction) {
AbstractFunction function = (AbstractFunction) arg;
if (function.isStrategy()) {
return new All(new StrategyFunction(function));
}
} else if (arg instanceof OverloadedFunctionResult) {
OverloadedFunctionResult res = (OverloadedFunctionResult) arg;
for (AbstractFunction function: res.iterable()) {
- if (function.isTypePreserving()) {
+ if (function.isStrategy()) {
return new All(new StrategyFunction(function));
}
}
}
throw new RuntimeException("Unexpected strategy argument "+arg);
}
}
| true | true | public static IValue makeAll(IValue arg) {
if (arg instanceof AbstractFunction) {
AbstractFunction function = (AbstractFunction) arg;
if (function.isStrategy()) {
return new All(new StrategyFunction(function));
}
} else if (arg instanceof OverloadedFunctionResult) {
OverloadedFunctionResult res = (OverloadedFunctionResult) arg;
for (AbstractFunction function: res.iterable()) {
if (function.isTypePreserving()) {
return new All(new StrategyFunction(function));
}
}
}
throw new RuntimeException("Unexpected strategy argument "+arg);
}
| public static IValue makeAll(IValue arg) {
if (arg instanceof AbstractFunction) {
AbstractFunction function = (AbstractFunction) arg;
if (function.isStrategy()) {
return new All(new StrategyFunction(function));
}
} else if (arg instanceof OverloadedFunctionResult) {
OverloadedFunctionResult res = (OverloadedFunctionResult) arg;
for (AbstractFunction function: res.iterable()) {
if (function.isStrategy()) {
return new All(new StrategyFunction(function));
}
}
}
throw new RuntimeException("Unexpected strategy argument "+arg);
}
|
diff --git a/src/StudentAssignment.java b/src/StudentAssignment.java
index 48cd643..2e7a8fb 100644
--- a/src/StudentAssignment.java
+++ b/src/StudentAssignment.java
@@ -1,46 +1,46 @@
// Author(s): Richard Ceus
// Date Modified: 4/10/12
// Filename: StudentAssignment.java
import java.util.*;
public class StudentAssignment extends Assignment
{
private double grade;
public StudentAssignment(Calendar date, int number)
{
super(date, number);
grade = 0.0;
}
public StudentAssignment(Assignment asst){
super(asst);
}
public double getGrade()
{
calculateGrade();
return grade;
}
public void calculateGrade()
{
- int correct;
- int total;
+ int correct = 0;
+ int total = 0;
for(int count = 0; count > questionList.size(); count++)
{
if (questionList.get(count).compareAnswers())
{
correct++;
}
total++;
}
grade = correct/total;
}
}
| true | true | public void calculateGrade()
{
int correct;
int total;
for(int count = 0; count > questionList.size(); count++)
{
if (questionList.get(count).compareAnswers())
{
correct++;
}
total++;
}
grade = correct/total;
}
| public void calculateGrade()
{
int correct = 0;
int total = 0;
for(int count = 0; count > questionList.size(); count++)
{
if (questionList.get(count).compareAnswers())
{
correct++;
}
total++;
}
grade = correct/total;
}
|
diff --git a/src/lang/LuaFoldingBuilder.java b/src/lang/LuaFoldingBuilder.java
index d70d5b1d..708d1b24 100644
--- a/src/lang/LuaFoldingBuilder.java
+++ b/src/lang/LuaFoldingBuilder.java
@@ -1,105 +1,106 @@
/*
* Copyright 2010 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang;
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaTableConstructor;
import com.sylvanaar.idea.Lua.lang.psi.statements.LuaFunctionDefinitionStatement;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static com.sylvanaar.idea.Lua.lang.lexer.LuaTokenTypes.LONGCOMMENT;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: Apr 10, 2010
* Time: 2:54:53 PM
*/
public class LuaFoldingBuilder implements FoldingBuilder {
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) {
List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
appendDescriptors(node, document, descriptors);
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
try {
if (isFoldableNode(node)) {
final PsiElement psiElement = node.getPsi();
if (psiElement instanceof LuaFunctionDefinitionStatement) {
LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement;
+ System.out.println(stmt.getText());
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1,
node.getTextRange().getEndOffset())));
}
if (psiElement instanceof LuaTableConstructor) {
LuaTableConstructor stmt = (LuaTableConstructor) psiElement;
- if (stmt.getTextLength() > 2)
+ if (stmt.getText().indexOf("\n")>0)
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getTextRange().getStartOffset() + 1,
node.getTextRange().getEndOffset() - 1)));
}
}
if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
ASTNode child = node.getFirstChildNode();
while (child != null) {
appendDescriptors(child, document, descriptors);
child = child.getTreeNext();
}
} catch (Exception ignored) {
}
}
private boolean isFoldableNode(ASTNode node) {
return node.getElementType() == LuaElementTypes.FUNCTION_DEFINITION ||
node.getElementType() == LuaElementTypes.TABLE_CONSTUCTOR;
}
@Override
public String getPlaceholderText(@NotNull ASTNode node) {
if (node.getElementType() == LONGCOMMENT)
return "comment";
return "...";
}
@Override
public boolean isCollapsedByDefault(@NotNull ASTNode node) {
return false;
}
}
| false | true | private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
try {
if (isFoldableNode(node)) {
final PsiElement psiElement = node.getPsi();
if (psiElement instanceof LuaFunctionDefinitionStatement) {
LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement;
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1,
node.getTextRange().getEndOffset())));
}
if (psiElement instanceof LuaTableConstructor) {
LuaTableConstructor stmt = (LuaTableConstructor) psiElement;
if (stmt.getTextLength() > 2)
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getTextRange().getStartOffset() + 1,
node.getTextRange().getEndOffset() - 1)));
}
}
if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
ASTNode child = node.getFirstChildNode();
while (child != null) {
appendDescriptors(child, document, descriptors);
child = child.getTreeNext();
}
} catch (Exception ignored) {
}
}
| private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
try {
if (isFoldableNode(node)) {
final PsiElement psiElement = node.getPsi();
if (psiElement instanceof LuaFunctionDefinitionStatement) {
LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement;
System.out.println(stmt.getText());
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1,
node.getTextRange().getEndOffset())));
}
if (psiElement instanceof LuaTableConstructor) {
LuaTableConstructor stmt = (LuaTableConstructor) psiElement;
if (stmt.getText().indexOf("\n")>0)
descriptors.add(new FoldingDescriptor(node,
new TextRange(stmt.getTextRange().getStartOffset() + 1,
node.getTextRange().getEndOffset() - 1)));
}
}
if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
ASTNode child = node.getFirstChildNode();
while (child != null) {
appendDescriptors(child, document, descriptors);
child = child.getTreeNext();
}
} catch (Exception ignored) {
}
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java b/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java
index 1843862e9..514e77c5f 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java
@@ -1,898 +1,898 @@
package uk.ac.starlink.ttools.taplint;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.xml.sax.SAXException;
import uk.ac.starlink.util.ByteList;
import uk.ac.starlink.vo.TableMeta;
import uk.ac.starlink.vo.TapQuery;
import uk.ac.starlink.vo.UwsJob;
import uk.ac.starlink.vo.UwsJobInfo;
import uk.ac.starlink.vo.UwsStage;
/**
* TapLint stage which submits and manipulates UWS jobs, mostly to check
* that the UWS operations are performing correctly.
*
* @author Mark Taylor
* @since 24 Jun 2011
*/
public class JobStage implements Stage {
private final MetadataHolder metaHolder_;
private final long pollMillis_;
// This expression pinched at random without testing from
// "http://www.pelagodesign.com/blog/2009/05/20/" +
// "iso-8601-date-validation-that-doesnt-suck/"
private final static Pattern ISO8601_REGEX = Pattern.compile(
"^([\\+-]?\\d{4}(?!\\d{2}\\b))"
+ "((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?"
+ "|W([0-4]\\d|5[0-2])(-?[1-7])?"
+ "|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))"
+ "([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)"
+ "([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?"
+ "([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
);
/**
* Constructor.
*
* @param metaHolder supplies table metadata at run time so we know
* what to query
* @param pollMillis number of milliseconds between polling attempts
* when waiting for a normal job to complete
*/
public JobStage( MetadataHolder metaHolder, long pollMillis ) {
metaHolder_ = metaHolder;
pollMillis_ = pollMillis;
}
public String getDescription() {
return "Test asynchronous UWS/TAP behaviour";
}
public void run( Reporter reporter, URL serviceUrl ) {
TableMeta[] tmetas = metaHolder_.getTableMetadata();
if ( tmetas == null || tmetas.length == 0 ) {
reporter.report( ReportType.FAILURE, "NOTM",
"No table metadata available "
+ "(earlier stages failed/skipped? "
+ " - will not attempt UWS tests" );
return;
}
new UwsRunner( reporter, serviceUrl, tmetas[ 0 ], pollMillis_ ).run();
}
/**
* Class which does the work for this stage.
*/
private static class UwsRunner implements Runnable {
private final Reporter reporter_;
private final URL serviceUrl_;
private final TableMeta tmeta_;
private final long poll_;
private final String shortAdql_;
private final String runId1_;
private final String runId2_;
/**
* Constructor.
*
* @param reporter destination for validation messages
* @param serviceUrl base URL of TAP service
* @param tmeta example table metadata
* @param poll number of milliseconds between polls when waiting
*/
UwsRunner( Reporter reporter, URL serviceUrl, TableMeta tmeta,
long poll ) {
reporter_ = reporter;
serviceUrl_ = serviceUrl;
tmeta_ = tmeta;
poll_ = poll;
shortAdql_ = "SELECT TOP 100 * FROM " + tmeta.getName();
runId1_ = "TAPLINT-001";
runId2_ = "TAPLINT-002";
}
/**
* Invokes subordinate checking tasks.
*/
public void run() {
checkCreateAbortDelete( shortAdql_ );
checkCreateDelete( shortAdql_ );
checkCreateRun( shortAdql_ );
}
/**
* Runs sequence which creates, aborts and then deletes a job.
*
* @param adql adql text for query
*/
private void checkCreateAbortDelete( String adql ) {
UwsJob job = createJob( adql );
if ( job == null ) {
return;
}
URL jobUrl = job.getJobUrl();
checkPhase( job, "PENDING" );
checkParameter( job, "REQUEST", "doQuery", true );
checkParameter( job, "RUNID", runId1_, false );
if ( postParameter( job, "runId", runId2_ ) ) {
checkParameter( job, "RUNID", runId2_, false );
}
if ( postPhase( job, "ABORT" ) ) {
checkPhase( job, "ABORTED" );
}
// should check 303 response here really
if ( postKeyValue( job, "", "ACTION", "DELETE" ) ) {
checkDeleted( job );
}
}
/**
* Runs sequence which creates and then deletes a job.
*
* @param adql adql text for query
*/
private void checkCreateDelete( String adql ) {
UwsJob job = createJob( adql );
if ( job == null ) {
return;
}
URL jobUrl = job.getJobUrl();
checkPhase( job, "PENDING" );
URLConnection conn;
try {
conn = jobUrl.openConnection();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "HTOF",
"Failed to contact " + jobUrl, e );
return;
}
if ( ! ( conn instanceof HttpURLConnection ) ) {
reporter_.report( ReportType.ERROR, "NOHT",
"Job url " + jobUrl + " not HTTP?" );
return;
}
HttpURLConnection hconn = (HttpURLConnection) conn;
int response;
try {
hconn.setRequestMethod( "DELETE" );
hconn.setInstanceFollowRedirects( false );
hconn.connect();
response = hconn.getResponseCode();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "HTDE",
"Failed to perform HTTP DELETE to " + jobUrl,
e );
return;
}
checkDeleted( job );
}
/**
* Runs sequence which creates and then runs a job.
*
* @param adql adql text for query
*/
private void checkCreateRun( String adql ) {
UwsJob job = createJob( adql );
if ( job == null ) {
return;
}
URL jobUrl = job.getJobUrl();
checkEndpoints( job );
checkPhase( job, "PENDING" );
if ( ! postPhase( job, "RUN" ) ) {
return;
}
String phase;
try {
job.readPhase();
phase = job.getLastPhase();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "RDPH",
"Can't read phase for job " + jobUrl, e );
return;
}
if ( ! new HashSet( Arrays.asList( new String[] {
"QUEUED", "EXECUTING", "SUSPENDED",
"ERROR", "COMPLETED",
} ) ).contains( phase ) ) {
String msg = new StringBuilder()
.append( "Incorrect phase " )
.append( phase )
.append( " for started job " )
.append( jobUrl )
.toString();
reporter_.report( ReportType.ERROR, "BAPH", msg );
}
if ( UwsStage.FINISHED == UwsStage.forPhase( phase ) ) {
reporter_.report( ReportType.INFO, "JOFI",
"Job completed immediately - "
+ "can't test phase progression" );
delete( job );
return;
}
waitForFinish( job );
}
/**
* Checks that a job has a given phase.
*
* @param job job to check
* @param mustPhase asserted phase string
*/
private void checkPhase( UwsJob job, String mustPhase ) {
URL phaseUrl = resourceUrl( job, "/phase" );
String resourcePhase = readTextContent( phaseUrl, true );
UwsJobInfo jobInfo = readJobInfo( job );
String infoPhase = jobInfo == null ? null : jobInfo.getPhase();
String phase = resourcePhase != null ? resourcePhase : infoPhase;
if ( phase != null ) {
if ( ! mustPhase.equals( phase ) ) {
String msg = new StringBuilder()
.append( "Phase " )
.append( phase )
.append( " != " )
.append( mustPhase )
.toString();
reporter_.report( ReportType.ERROR, "PHUR", msg );
}
}
if ( infoPhase != null && resourcePhase != null &&
! ( infoPhase.equals( resourcePhase ) ) ) {
String msg = new StringBuilder()
.append( "Phase mismatch between job info " )
.append( "and /phase URL " )
.append( '(' )
.append( infoPhase )
.append( " != " )
.append( resourcePhase )
.append( ')' )
.toString();
reporter_.report( ReportType.ERROR, "JDPH", msg );
}
}
/**
* Checks that a job parameter has a given value.
*
* @param job job to check
* @param name job parameter name
* @param value asserted parameter value
* @param mandatory true iff parameter must be supported by TAP
* implementation
*/
private void checkParameter( UwsJob job, final String name,
final String mustValue,
boolean mandatory ) {
UwsJobInfo jobInfo = readJobInfo( job );
if ( jobInfo == null ) {
return;
}
UwsJobInfo.Parameter param =
getParamMap( jobInfo ).get( name.toUpperCase() );
String actualValue = param == null ? null : param.getValue();
if ( mustValue == null ) {
if ( actualValue == null ) {
// ok
}
else {
String msg = new StringBuilder()
.append( "Parameter " )
.append( name )
.append( " has value " )
.append( actualValue )
.append( " not blank in job document" )
.toString();
reporter_.report( ReportType.ERROR, "PANZ", msg );
}
}
else if ( actualValue == null && ! mandatory ) {
// ok
}
else if ( ! mustValue.equals( actualValue ) ) {
String msg = new StringBuilder()
.append( "Parameter " )
.append( name )
.append( " has value " )
.append( actualValue )
.append( " not " )
.append( mustValue )
.append( " in job document" )
.toString();
reporter_.report( ReportType.ERROR, "PAMM", msg );
}
}
/**
* Perform checks of resource declared types and contents for various
* job sub-resources.
*
* @param job job to check
*/
private void checkEndpoints( UwsJob job ) {
/* Check and read the job document. */
URL jobUrl = job.getJobUrl();
readContent( jobUrl, "text/xml", true );
UwsJobInfo jobInfo;
try {
jobInfo = job.readJob();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "JDIO",
"Error reading job document " + jobUrl, e );
return;
}
catch ( SAXException e ) {
reporter_.report( ReportType.ERROR, "JDSX",
"Error parsing job document " + jobUrl, e );
return;
}
if ( jobInfo == null ) {
reporter_.report( ReportType.ERROR, "JDNO",
"No job document found " + jobUrl );
return;
}
/* Check the job ID is consistent between the job URL and
* job info content. */
if ( ! jobUrl.toString().endsWith( "/" + jobInfo.getJobId() ) ) {
String msg = new StringBuilder()
.append( "Job ID mismatch; " )
.append( jobInfo.getJobId() )
.append( " is not final path element of " )
.append( jobUrl )
.toString();
reporter_.report( ReportType.ERROR, "JDID", msg );
}
/* Check the type of the quote resource. */
URL quoteUrl = resourceUrl( job, "/quote" );
String quote = readTextContent( quoteUrl, true );
/* Check the type and content of the executionduration, and
* whether it matches that in the job document. */
URL durationUrl = resourceUrl( job, "/executionduration" );
String duration = readTextContent( durationUrl, true );
checkInt( durationUrl, duration );
if ( ! equals( duration, jobInfo.getExecutionDuration() ) ) {
String msg = new StringBuilder()
.append( "Execution duration mismatch between job info " )
.append( "and /executionduration URL " )
.append( '(' )
.append( jobInfo.getExecutionDuration() )
.append( " != " )
.append( duration )
.append( ')' )
.toString();
reporter_.report( ReportType.ERROR, "JDED", msg );
}
/* Check the type and content of the destruction time, and
* whether it matches that in the job document. */
URL destructUrl = resourceUrl( job, "/destruction" );
String destruct = readTextContent( destructUrl, true );
checkDateTime( destructUrl, destruct );
if ( ! equals( destruct, jobInfo.getDestruction() ) ) {
String msg = new StringBuilder()
.append( "Destruction time mismatch between job info " )
.append( "and /destruction URL " )
.append( '(' )
.append( jobInfo.getDestruction() )
.append( " != " )
.append( destruct )
.append( ')' )
.toString();
reporter_.report( ReportType.ERROR, "JDDE", msg );
}
}
/**
* Checks that a job has been deleted, and no longer exists.
*
* @param job job to check
*/
private void checkDeleted( UwsJob job ) {
URL jobUrl = job.getJobUrl();
URLConnection conn;
try {
conn = jobUrl.openConnection();
conn.connect();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "DEOP",
"Can't open connection to " + jobUrl, e );
return;
}
if ( conn instanceof HttpURLConnection ) {
int code;
try {
code = ((HttpURLConnection) conn).getResponseCode();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "DEHT",
"Bad HTTP connection to " + jobUrl, e );
return;
}
if ( code != 404 ) {
String msg = new StringBuilder()
.append( "Deleted job " )
.append( "gives HTTP response " )
.append( code )
.append( " not 404" )
.append( " for " )
.append( jobUrl )
.toString();
reporter_.report( ReportType.ERROR, "DENO", msg );
}
}
else {
reporter_.report( ReportType.ERROR, "NOHT",
"Job " + jobUrl + " not HTTP?" );
}
}
/**
* Returns the URL of a job subresource, supressing exceptions.
*
* @param job job object
* @param subResource resource subpath, starting "/"
* @return resource URL, or null in the unlikely event of failure
*/
private URL resourceUrl( UwsJob job, String subResource ) {
String urlStr = job.getJobUrl() + subResource;
try {
return new URL( urlStr );
}
catch ( MalformedURLException e ) {
reporter_.report( ReportType.FAILURE, "MURL",
"Bad URL " + urlStr + "??", e );
return null;
}
}
/**
* Sets a parameter value for a UWS job.
*
* @param job UWS job
* @param name parameter name
* @param value parameter value
* @return true iff parameter was set successfully
*/
private boolean postParameter( UwsJob job, String name, String value ) {
return postKeyValue( job, "/parameters", name, value );
}
/**
* Posts the phase for a UWS job.
*
* @param job UWS job
* @param phase UWS phase string
* @return true iff phase was posted successfully
*/
private boolean postPhase( UwsJob job, String phase ) {
return postKeyValue( job, "/phase", "PHASE", phase );
}
/**
* POSTs a key=value pair to a resource URL relating to a UWS job.
*
* @param job UWS job
* @param subResource relative path of resource within job
* (include leading "/")
* @param key key string
* @param value value string
* @return true iff POST completed successfully
*/
private boolean postKeyValue( UwsJob job, String subResource,
String key, String value ) {
URL url;
try {
url = new URL( job.getJobUrl() + subResource );
}
catch ( MalformedURLException e ) {
throw (AssertionError) new AssertionError().initCause( e );
}
Map<String,String> map = new HashMap<String,String>();
map.put( key, value );
int code;
String responseMsg;
try {
HttpURLConnection conn = UwsJob.postUnipartForm( url, map );
code = conn.getResponseCode();
responseMsg = conn.getResponseMessage();
}
catch ( IOException e ) {
String msg = new StringBuilder()
.append( "Failed to POST parameter " )
.append( key )
.append( "=" )
.append( value )
.append( " to " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "POER", msg, e );
return false;
}
if ( code >= 400 ) {
String msg = new StringBuilder()
.append( "Error response " )
.append( code )
.append( " " )
.append( responseMsg )
.append( " for POST " )
.append( key )
.append( "=" )
.append( value )
.append( " to " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "PORE", msg );
return false;
}
String msg = new StringBuilder()
.append( "POSTed " )
.append( key )
.append( "=" )
.append( value )
.append( " to " )
.append( url )
.toString();
reporter_.report( ReportType.INFO, "POPA", msg );
return true;
}
/**
* Deletes a job.
*
* @param job UWS job
*/
private void delete( UwsJob job ) {
try {
job.postDelete();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "DENO",
"Failed to delete job " + job.getJobUrl(),
e );
return;
}
checkDeleted( job );
}
/**
* Waits for a running job to complete.
*
* @param job UWS job
*/
private void waitForFinish( UwsJob job ) {
URL jobUrl = job.getJobUrl();
while ( UwsStage.forPhase( job.getLastPhase() )
!= UwsStage.FINISHED ) {
String phase = job.getLastPhase();
UwsStage stage = UwsStage.forPhase( phase );
switch ( stage ) {
case UNSTARTED:
reporter_.report( ReportType.ERROR, "RUPH",
"Incorrect phase " + phase
+ " for started job " + jobUrl );
return;
case ILLEGAL:
case UNKNOWN:
reporter_.report( ReportType.ERROR, "BAPH",
"Bad phase " + phase
+ " for job " + jobUrl );
return;
case RUNNING:
try {
Thread.sleep( poll_ );
}
catch ( InterruptedException e ) {
reporter_.report( ReportType.FAILURE, "INTR",
"Interrupted??" );
return;
}
break;
case FINISHED:
break;
default:
throw new AssertionError();
}
try {
job.readPhase();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "RDPH",
"Can't read phase for job " + jobUrl );
return;
}
}
}
/**
* Constructs a name->param map from a UwsJobInfo object.
*
* @param jobInfo job metadata structure describing a UWS job
* @return name->param map
*/
private Map<String,UwsJobInfo.Parameter>
getParamMap( UwsJobInfo jobInfo ) {
Map<String,UwsJobInfo.Parameter> paramMap =
new LinkedHashMap<String,UwsJobInfo.Parameter>();
if ( jobInfo != null && jobInfo.getParameters() != null ) {
UwsJobInfo.Parameter[] params = jobInfo.getParameters();
for ( int ip = 0; ip < params.length; ip++ ) {
UwsJobInfo.Parameter param = params[ ip ];
String name = param.getId();
if ( name == null || name.length() == 0 ) {
reporter_.report( ReportType.ERROR, "PANO",
"Parameter with no name" );
}
else {
String upName = param.getId().toUpperCase();
if ( paramMap.containsKey( upName ) ) {
String msg = new StringBuilder()
.append( "Duplicate parameter " )
.append( upName )
.append( " in job parameters list" )
.toString();
reporter_.report( ReportType.ERROR, "PADU",
msg );
}
else {
paramMap.put( upName, param );
}
}
}
}
return paramMap;
}
/**
* Reads the metadata object for a job.
*
* @param job UWS job
* @return job info, or null if it couldn't be read
*/
private UwsJobInfo readJobInfo( UwsJob job ) {
try {
return job.readJob();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "JBIO",
"Error reading job info", e );
return null;
}
catch ( SAXException e ) {
reporter_.report( ReportType.ERROR, "JBSP",
"Error parsing job info", e );
return null;
}
}
/**
* Creates a UWS job based on a given adql query string.
*
* @param adql query text
* @return new job, or null if there was an error
*/
private UwsJob createJob( String adql ) {
TapQuery tq;
Map<String,String> paramMap = new LinkedHashMap<String,String>();
paramMap.put( "RUNID", runId1_ );
try {
tq = new TapQuery( serviceUrl_, adql, paramMap, null, 0 );
}
catch ( IOException e ) {
throw new AssertionError( "no upload!" );
}
UwsJob job;
try {
job = UwsJob.createJob( tq.getServiceUrl() + "/async",
tq.getStringParams(),
tq.getStreamParams() );
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "QFAA",
"Failed to submit TAP query "
+ shortAdql_, e );
return null;
}
reporter_.report( ReportType.INFO, "CJOB",
"Created new job " + job.getJobUrl() );
return job;
}
/**
* Equality utility for two strings.
*
* @param s1 string 1, may be null
* @param s2 string 2, may be null
* @return true iff they are equal
*/
private boolean equals( String s1, String s2 ) {
return s1 == null || s1.trim().length() == 0
? ( s2 == null || s2.trim().length() == 0 )
: s1.equals( s2 );
}
/**
* Checks that the content of a given URL is an integer.
*
* @param url source of text, for reporting
* @param txt text content
*/
private void checkInt( URL url, String txt ) {
try {
Long.parseLong( txt );
}
catch ( NumberFormatException e ) {
String msg = new StringBuilder()
.append( "Not integer content " )
.append( '"' )
.append( txt )
.append( '"' )
.append( " from " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "IFMT", msg );
}
}
/**
* Checks that the content of a given URL is a ISO-8601 date.
*
* @param url source of text, for reporting
* @param txt text content
*/
private void checkDateTime( URL url, String txt ) {
if ( txt != null ) {
if ( ! ISO8601_REGEX.matcher( txt ).matches() ) {
String msg = new StringBuilder()
.append( "Not ISO-8601 content " )
.append( '"' )
.append( txt )
.append( '"' )
.append( " from " )
.append( url )
.toString();
reporter_.report( ReportType.WARNING, "TFMT", msg );
}
}
}
/**
* Returns the content of a given URL, checking that it has text/plain
* declared MIME type.
*
* @param url URL to read
* @param mustExist true if non-existence should trigger error report
* @return content string (assumed UTF-8), or null
*/
private String readTextContent( URL url, boolean mustExist ) {
byte[] buf = readContent( url, "text/plain", mustExist );
try {
return buf == null ? null : new String( buf, "UTF-8" );
}
catch ( UnsupportedEncodingException e ) {
reporter_.report( ReportType.FAILURE, "UTF8",
"Unknown encoding UTF-8??", e );
return null;
}
}
/**
* Reads the content of a URL and checks that it has a given declared
* MIME type.
*
* @param url URL to read
* @param mimeType required declared Content-Type
* @param mustExist true if non-existence should trigger error report
* @return content bytes, or null
*/
private byte[] readContent( URL url, String mimeType,
boolean mustExist ) {
if ( url == null ) {
return null;
}
HttpURLConnection hconn;
int responseCode;
String responseMsg;
try {
URLConnection conn = url.openConnection();
conn = TapQuery.followRedirects( conn );
if ( ! ( conn instanceof HttpURLConnection ) ) {
reporter_.report( ReportType.WARNING, "HURL",
"Redirect to non-HTTP URL? "
+ conn.getURL() );
return null;
}
hconn = (HttpURLConnection) conn;
hconn.connect();
responseCode = hconn.getResponseCode();
responseMsg = hconn.getResponseMessage();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "EURL",
"Error contacting URL " + url );
return null;
}
if ( responseCode != 200 ) {
if ( mustExist ) {
String msg = new StringBuilder()
.append( "Non-OK response " )
.append( responseCode )
.append( " " )
.append( responseMsg )
.append( " from " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "NFND", msg );
}
return null;
}
InputStream in = null;
byte[] buf;
try {
in = new BufferedInputStream( hconn.getInputStream() );
ByteList blist = new ByteList();
for ( int b; ( b = in.read() ) >= 0; ) {
blist.add( (byte) b );
}
buf = blist.toByteArray();
}
catch ( IOException e ) {
reporter_.report( ReportType.WARNING, "RDIO",
"Error reading resource " + url );
buf = null;
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
}
}
}
String ctype = hconn.getContentType();
- if ( ctype == null && ctype.trim().length() == 0 ) {
+ if ( ctype == null || ctype.trim().length() == 0 ) {
reporter_.report( ReportType.WARNING, "NOCT",
"No Content-Type header for " + url );
}
else if ( ! ctype.startsWith( mimeType ) ) {
String msg = new StringBuilder()
.append( "Incorrect Content-Type " )
.append( ctype )
.append( " != " )
.append( mimeType )
.append( " for " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "GMIM", msg );
return buf;
}
return buf;
}
}
}
| true | true | private byte[] readContent( URL url, String mimeType,
boolean mustExist ) {
if ( url == null ) {
return null;
}
HttpURLConnection hconn;
int responseCode;
String responseMsg;
try {
URLConnection conn = url.openConnection();
conn = TapQuery.followRedirects( conn );
if ( ! ( conn instanceof HttpURLConnection ) ) {
reporter_.report( ReportType.WARNING, "HURL",
"Redirect to non-HTTP URL? "
+ conn.getURL() );
return null;
}
hconn = (HttpURLConnection) conn;
hconn.connect();
responseCode = hconn.getResponseCode();
responseMsg = hconn.getResponseMessage();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "EURL",
"Error contacting URL " + url );
return null;
}
if ( responseCode != 200 ) {
if ( mustExist ) {
String msg = new StringBuilder()
.append( "Non-OK response " )
.append( responseCode )
.append( " " )
.append( responseMsg )
.append( " from " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "NFND", msg );
}
return null;
}
InputStream in = null;
byte[] buf;
try {
in = new BufferedInputStream( hconn.getInputStream() );
ByteList blist = new ByteList();
for ( int b; ( b = in.read() ) >= 0; ) {
blist.add( (byte) b );
}
buf = blist.toByteArray();
}
catch ( IOException e ) {
reporter_.report( ReportType.WARNING, "RDIO",
"Error reading resource " + url );
buf = null;
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
}
}
}
String ctype = hconn.getContentType();
if ( ctype == null && ctype.trim().length() == 0 ) {
reporter_.report( ReportType.WARNING, "NOCT",
"No Content-Type header for " + url );
}
else if ( ! ctype.startsWith( mimeType ) ) {
String msg = new StringBuilder()
.append( "Incorrect Content-Type " )
.append( ctype )
.append( " != " )
.append( mimeType )
.append( " for " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "GMIM", msg );
return buf;
}
return buf;
}
| private byte[] readContent( URL url, String mimeType,
boolean mustExist ) {
if ( url == null ) {
return null;
}
HttpURLConnection hconn;
int responseCode;
String responseMsg;
try {
URLConnection conn = url.openConnection();
conn = TapQuery.followRedirects( conn );
if ( ! ( conn instanceof HttpURLConnection ) ) {
reporter_.report( ReportType.WARNING, "HURL",
"Redirect to non-HTTP URL? "
+ conn.getURL() );
return null;
}
hconn = (HttpURLConnection) conn;
hconn.connect();
responseCode = hconn.getResponseCode();
responseMsg = hconn.getResponseMessage();
}
catch ( IOException e ) {
reporter_.report( ReportType.ERROR, "EURL",
"Error contacting URL " + url );
return null;
}
if ( responseCode != 200 ) {
if ( mustExist ) {
String msg = new StringBuilder()
.append( "Non-OK response " )
.append( responseCode )
.append( " " )
.append( responseMsg )
.append( " from " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "NFND", msg );
}
return null;
}
InputStream in = null;
byte[] buf;
try {
in = new BufferedInputStream( hconn.getInputStream() );
ByteList blist = new ByteList();
for ( int b; ( b = in.read() ) >= 0; ) {
blist.add( (byte) b );
}
buf = blist.toByteArray();
}
catch ( IOException e ) {
reporter_.report( ReportType.WARNING, "RDIO",
"Error reading resource " + url );
buf = null;
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
}
}
}
String ctype = hconn.getContentType();
if ( ctype == null || ctype.trim().length() == 0 ) {
reporter_.report( ReportType.WARNING, "NOCT",
"No Content-Type header for " + url );
}
else if ( ! ctype.startsWith( mimeType ) ) {
String msg = new StringBuilder()
.append( "Incorrect Content-Type " )
.append( ctype )
.append( " != " )
.append( mimeType )
.append( " for " )
.append( url )
.toString();
reporter_.report( ReportType.ERROR, "GMIM", msg );
return buf;
}
return buf;
}
|
diff --git a/src/java/net/percederberg/mibble/MibLoaderLog.java b/src/java/net/percederberg/mibble/MibLoaderLog.java
index 53e3089..94acc28 100644
--- a/src/java/net/percederberg/mibble/MibLoaderLog.java
+++ b/src/java/net/percederberg/mibble/MibLoaderLog.java
@@ -1,491 +1,491 @@
/*
* MibLoaderLog.java
*
* This work 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 work 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
*
* Copyright (c) 2004 Per Cederberg. All rights reserved.
*/
package net.percederberg.mibble;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import net.percederberg.grammatica.parser.ParseException;
import net.percederberg.grammatica.parser.ParserLogException;
/**
* A MIB loader log. This class contains error and warning messages
* from loading a MIB file and all imports not previously loaded.
*
* @author Per Cederberg, <per at percederberg dot net>
* @version 2.6
* @since 2.0
*/
public class MibLoaderLog {
/**
* The log entries.
*/
private ArrayList entries = new ArrayList();
/**
* The log error count.
*/
private int errors = 0;
/**
* The log warning count.
*/
private int warnings = 0;
/**
* Creates a new loader log without entries.
*/
public MibLoaderLog() {
// Nothing initialization needed
}
/**
* Returns the number of errors in the log.
*
* @return the number of errors in the log
*/
public int errorCount() {
return errors;
}
/**
* Returns the number of warnings in the log.
*
* @return the number of warnings in the log
*/
public int warningCount() {
return warnings;
}
/**
* Adds a log entry to this log.
*
* @param entry the log entry to add
*/
public void add(LogEntry entry) {
if (entry.isError()) {
errors++;
}
if (entry.isWarning()) {
warnings++;
}
entries.add(entry);
}
/**
* Adds an internal error message to the log. Internal errors are
* only issued when possible bugs are encountered. They are
* counted as errors.
*
* @param location the file location
* @param message the error message
*/
public void addInternalError(FileLocation location, String message) {
add(new LogEntry(LogEntry.INTERNAL_ERROR, location, message));
}
/**
* Adds an internal error message to the log. Internal errors are
* only issued when possible bugs are encountered. They are
* counted as errors.
*
* @param file the file affected
* @param message the error message
*/
public void addInternalError(File file, String message) {
addInternalError(new FileLocation(file), message);
}
/**
* Adds an error message to the log.
*
* @param location the file location
* @param message the error message
*/
public void addError(FileLocation location, String message) {
add(new LogEntry(LogEntry.ERROR, location, message));
}
/**
* Adds an error message to the log.
*
* @param file the file affected
* @param line the line number
* @param column the column number
* @param message the error message
*/
public void addError(File file, int line, int column, String message) {
addError(new FileLocation(file, line, column), message);
}
/**
* Adds a warning message to the log.
*
* @param location the file location
* @param message the warning message
*/
public void addWarning(FileLocation location, String message) {
add(new LogEntry(LogEntry.WARNING, location, message));
}
/**
* Adds a warning message to the log.
*
* @param file the file affected
* @param line the line number
* @param column the column number
* @param message the warning message
*/
public void addWarning(File file, int line, int column, String message) {
addWarning(new FileLocation(file, line, column), message);
}
/**
* Adds all log entries from another log.
*
* @param log the MIB loader log
*/
public void addAll(MibLoaderLog log) {
for (int i = 0; i < log.entries.size(); i++) {
add((LogEntry) log.entries.get(i));
}
}
/**
* Adds all errors from a parser log exception.
*
* @param file the file affected
* @param log the parser log exception
*/
void addAll(File file, ParserLogException log) {
ParseException e;
for (int i = 0; i < log.getErrorCount(); i++) {
e = log.getError(i);
addError(file, e.getLine(), e.getColumn(), e.getErrorMessage());
}
}
/**
* Returns an iterator with all the log entries. The iterator
* will only return LogEntry instances.
*
* @return an iterator with all the log entries
*
* @see LogEntry
*
* @since 2.2
*/
public Iterator entries() {
return entries.iterator();
}
/**
* Prints all log entries to the specified output stream.
*
* @param output the output stream to use
*/
public void printTo(PrintStream output) {
printTo(new PrintWriter(output));
}
/**
* Prints all log entries to the specified output stream.
*
* @param output the output stream to use
*/
public void printTo(PrintWriter output) {
printTo(output, 70);
}
/**
* Prints all log entries to the specified output stream.
*
* @param output the output stream to use
* @param margin the print margin
*
* @since 2.2
*/
public void printTo(PrintWriter output, int margin) {
StringBuffer buffer = new StringBuffer();
LogEntry entry;
String str;
for (int i = 0; i < entries.size(); i++) {
entry = (LogEntry) entries.get(i);
buffer.setLength(0);
switch (entry.getType()) {
case LogEntry.ERROR:
buffer.append("Error: ");
break;
case LogEntry.WARNING:
buffer.append("Warning: ");
break;
default:
buffer.append("Internal Error: ");
break;
}
buffer.append("in ");
buffer.append(relativeFilename(entry.getFile()));
if (entry.getLineNumber() > 0) {
buffer.append(": line ");
buffer.append(entry.getLineNumber());
}
buffer.append(":\n");
str = linebreakString(entry.getMessage(), " ", margin);
buffer.append(str);
str = entry.readLine();
- if (str != null) {
+ if (str != null && str.length() >= entry.getColumnNumber()) {
buffer.append("\n\n");
buffer.append(str);
buffer.append("\n");
for (int j = 1; j < entry.getColumnNumber(); j++) {
if (str.charAt(j - 1) == '\t') {
buffer.append("\t");
} else {
buffer.append(" ");
}
}
buffer.append("^");
}
output.println(buffer.toString());
}
output.flush();
}
/**
* Creates a relative file name from a file. This method will
* return the absolute file name if the file unless the current
* directory is a parent to the file.
*
* @param file the file to calculate relative name for
*
* @return the relative name if found, or
* the absolute name otherwise
*/
private String relativeFilename(File file) {
String currentPath;
String filePath;
if (file == null) {
return "<unknown file>";
}
try {
currentPath = new File(".").getCanonicalPath();
filePath = file.getCanonicalPath();
if (filePath.startsWith(currentPath)) {
filePath = filePath.substring(currentPath.length());
if (filePath.charAt(0) == '/'
|| filePath.charAt(0) == '\\') {
return filePath.substring(1);
} else {
return filePath;
}
}
} catch (IOException e) {
// Do nothing
}
return file.toString();
}
/**
* Breaks a string into multiple lines. This method will also add
* a prefix to each line in the resulting string. The prefix
* length will be taken into account when breaking the line. Line
* breaks will only be inserted as replacements for space
* characters.
*
* @param str the string to line break
* @param prefix the prefix to add to each line
* @param length the maximum line length
*
* @return the new formatted string
*/
private String linebreakString(String str, String prefix, int length) {
StringBuffer buffer = new StringBuffer();
int pos;
while (str.length() + prefix.length() > length) {
pos = str.lastIndexOf(' ', length - prefix.length());
if (pos < 0) {
pos = str.indexOf(' ');
if (pos < 0) {
break;
}
}
buffer.append(prefix);
buffer.append(str.substring(0, pos));
str = str.substring(pos + 1);
buffer.append("\n");
}
buffer.append(prefix);
buffer.append(str);
return buffer.toString();
}
/**
* A log entry. This class holds all the details in an error or a
* warning log entry.
*
* @author Per Cederberg, <per at percederberg dot net>
* @version 2.2
* @since 2.2
*/
public class LogEntry {
/**
* The internal error log entry type constant.
*/
public static final int INTERNAL_ERROR = 1;
/**
* The error log entry type constant.
*/
public static final int ERROR = 2;
/**
* The warning log entry type constant.
*/
public static final int WARNING = 3;
/**
* The log entry type.
*/
private int type;
/**
* The log entry file reference.
*/
private FileLocation location;
/**
* The log entry message.
*/
private String message;
/**
* Creates a new log entry.
*
* @param type the log entry type
* @param location the log entry file reference
* @param message the log entry message
*/
public LogEntry(int type, FileLocation location, String message) {
this.type = type;
if (location == null || location.getFile() == null) {
this.location = new FileLocation(new File("<unknown file>"));
} else {
this.location = location;
}
this.message = message;
}
/**
* Checks if this is an error log entry.
*
* @return true if this is an error log entry, or
* false otherwise
*/
public boolean isError() {
return type == INTERNAL_ERROR || type == ERROR;
}
/**
* Checks if this is a warning log entry.
*
* @return true if this is a warning log entry, or
* false otherwise
*/
public boolean isWarning() {
return type == WARNING;
}
/**
* Returns the log entry type.
*
* @return the log entry type
*
* @see #INTERNAL_ERROR
* @see #ERROR
* @see #WARNING
*/
public int getType() {
return type;
}
/**
* Returns the file this entry applies to.
*
* @return the file affected
*/
public File getFile() {
return location.getFile();
}
/**
* Returns the line number.
*
* @return the line number
*/
public int getLineNumber() {
return location.getLineNumber();
}
/**
* Returns the column number.
*
* @return the column number
*/
public int getColumnNumber() {
return location.getColumnNumber();
}
/**
* Returns the log entry message.
*
* @return the log entry message
*/
public String getMessage() {
return message;
}
/**
* Reads the line from the referenced file. If the file couldn't
* be opened or read correctly, null will be returned. The line
* will NOT contain the terminating '\n' character.
*
* @return the line read, or
* null if not found
*/
public String readLine() {
return location.readLine();
}
}
}
| true | true | public void printTo(PrintWriter output, int margin) {
StringBuffer buffer = new StringBuffer();
LogEntry entry;
String str;
for (int i = 0; i < entries.size(); i++) {
entry = (LogEntry) entries.get(i);
buffer.setLength(0);
switch (entry.getType()) {
case LogEntry.ERROR:
buffer.append("Error: ");
break;
case LogEntry.WARNING:
buffer.append("Warning: ");
break;
default:
buffer.append("Internal Error: ");
break;
}
buffer.append("in ");
buffer.append(relativeFilename(entry.getFile()));
if (entry.getLineNumber() > 0) {
buffer.append(": line ");
buffer.append(entry.getLineNumber());
}
buffer.append(":\n");
str = linebreakString(entry.getMessage(), " ", margin);
buffer.append(str);
str = entry.readLine();
if (str != null) {
buffer.append("\n\n");
buffer.append(str);
buffer.append("\n");
for (int j = 1; j < entry.getColumnNumber(); j++) {
if (str.charAt(j - 1) == '\t') {
buffer.append("\t");
} else {
buffer.append(" ");
}
}
buffer.append("^");
}
output.println(buffer.toString());
}
output.flush();
}
| public void printTo(PrintWriter output, int margin) {
StringBuffer buffer = new StringBuffer();
LogEntry entry;
String str;
for (int i = 0; i < entries.size(); i++) {
entry = (LogEntry) entries.get(i);
buffer.setLength(0);
switch (entry.getType()) {
case LogEntry.ERROR:
buffer.append("Error: ");
break;
case LogEntry.WARNING:
buffer.append("Warning: ");
break;
default:
buffer.append("Internal Error: ");
break;
}
buffer.append("in ");
buffer.append(relativeFilename(entry.getFile()));
if (entry.getLineNumber() > 0) {
buffer.append(": line ");
buffer.append(entry.getLineNumber());
}
buffer.append(":\n");
str = linebreakString(entry.getMessage(), " ", margin);
buffer.append(str);
str = entry.readLine();
if (str != null && str.length() >= entry.getColumnNumber()) {
buffer.append("\n\n");
buffer.append(str);
buffer.append("\n");
for (int j = 1; j < entry.getColumnNumber(); j++) {
if (str.charAt(j - 1) == '\t') {
buffer.append("\t");
} else {
buffer.append(" ");
}
}
buffer.append("^");
}
output.println(buffer.toString());
}
output.flush();
}
|
diff --git a/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java b/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java
index 111cc429..3f96467b 100644
--- a/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java
+++ b/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java
@@ -1,83 +1,92 @@
/**
* This file is part of the Paxle project.
* Visit http://www.paxle.net for more information.
* Copyright 2007-2009 the original author or authors.
*
* Licensed under the terms of the Common Public License 1.0 ("CPL 1.0").
* Any use, reproduction or distribution of this program constitutes the recipient's acceptance of this agreement.
* The full license text is available under http://www.opensource.org/licenses/cpl1.0.txt
* or in the file LICENSE.txt in the root directory of the Paxle distribution.
*
* Unless required by applicable law or agreed to in writing, this software is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.paxle.parser.zip.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.paxle.core.doc.IParserDocument;
import org.paxle.core.doc.ParserDocument;
import org.paxle.core.io.IOTools;
import org.paxle.parser.ISubParser;
import org.paxle.parser.ParserContext;
import org.paxle.parser.ParserException;
import org.paxle.parser.iotools.SubParserDocOutputStream;
/**
* @scr.component
* @scr.service interface="org.paxle.parser.ISubParser"
* @scr.property name="MimeTypes" private="true"
* values.1="application/zip"
* values.2="application/x-zip"
* values.3="application/x-zip-compressed"
* values.4="application/java-archive"
*/
public class ZipParser implements ISubParser {
public IParserDocument parse(URI location, String charset, InputStream is)
throws ParserException, UnsupportedEncodingException, IOException
{
final ParserContext context = ParserContext.getCurrentContext();
final IParserDocument pdoc = new ParserDocument();
final ZipInputStream zis = new ZipInputStream(is);
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
if (ze.isDirectory()) continue;
- final SubParserDocOutputStream sos = new SubParserDocOutputStream(
- context.getTempFileManager(),
- context.getCharsetDetector(),
- pdoc, location, ze.getName(), ze.getSize());
+ final long size = ze.getSize();
+ final SubParserDocOutputStream sos;
+ if (size == -1) {
+ sos = new SubParserDocOutputStream(
+ context.getTempFileManager(),
+ context.getCharsetDetector(),
+ pdoc, location, ze.getName());
+ } else {
+ sos = new SubParserDocOutputStream(
+ context.getTempFileManager(),
+ context.getCharsetDetector(),
+ pdoc, location, ze.getName(), size);
+ }
try {
- IOTools.copy(zis, sos, ze.getSize());
+ IOTools.copy(zis, sos, size); // size == -1 is ok here
} finally {
try { sos.close(); } catch (IOException e) {
if (e.getCause() instanceof ParserException) {
throw (ParserException)e.getCause();
} else {
throw e;
}
}
}
}
pdoc.setStatus(IParserDocument.Status.OK);
return pdoc;
}
public IParserDocument parse(URI location, String charset, File content)
throws ParserException, UnsupportedEncodingException, IOException {
final FileInputStream fis = new FileInputStream(content);
try {
return parse(location, charset, fis);
} finally {
fis.close();
}
}
}
| false | true | public IParserDocument parse(URI location, String charset, InputStream is)
throws ParserException, UnsupportedEncodingException, IOException
{
final ParserContext context = ParserContext.getCurrentContext();
final IParserDocument pdoc = new ParserDocument();
final ZipInputStream zis = new ZipInputStream(is);
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
if (ze.isDirectory()) continue;
final SubParserDocOutputStream sos = new SubParserDocOutputStream(
context.getTempFileManager(),
context.getCharsetDetector(),
pdoc, location, ze.getName(), ze.getSize());
try {
IOTools.copy(zis, sos, ze.getSize());
} finally {
try { sos.close(); } catch (IOException e) {
if (e.getCause() instanceof ParserException) {
throw (ParserException)e.getCause();
} else {
throw e;
}
}
}
}
pdoc.setStatus(IParserDocument.Status.OK);
return pdoc;
}
| public IParserDocument parse(URI location, String charset, InputStream is)
throws ParserException, UnsupportedEncodingException, IOException
{
final ParserContext context = ParserContext.getCurrentContext();
final IParserDocument pdoc = new ParserDocument();
final ZipInputStream zis = new ZipInputStream(is);
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
if (ze.isDirectory()) continue;
final long size = ze.getSize();
final SubParserDocOutputStream sos;
if (size == -1) {
sos = new SubParserDocOutputStream(
context.getTempFileManager(),
context.getCharsetDetector(),
pdoc, location, ze.getName());
} else {
sos = new SubParserDocOutputStream(
context.getTempFileManager(),
context.getCharsetDetector(),
pdoc, location, ze.getName(), size);
}
try {
IOTools.copy(zis, sos, size); // size == -1 is ok here
} finally {
try { sos.close(); } catch (IOException e) {
if (e.getCause() instanceof ParserException) {
throw (ParserException)e.getCause();
} else {
throw e;
}
}
}
}
pdoc.setStatus(IParserDocument.Status.OK);
return pdoc;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/LeicaReader.java b/components/bio-formats/src/loci/formats/in/LeicaReader.java
index 423921ef9..02ab41237 100644
--- a/components/bio-formats/src/loci/formats/in/LeicaReader.java
+++ b/components/bio-formats/src/loci/formats/in/LeicaReader.java
@@ -1,1135 +1,1135 @@
//
// LeicaReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.text.*;
import java.util.*;
import loci.common.*;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
/**
* LeicaReader is the file format reader for Leica files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class LeicaReader extends FormatReader {
// -- Constants -
public static final String[] LEI_SUFFIX = {"lei"};
/** All Leica TIFFs have this tag. */
private static final int LEICA_MAGIC_TAG = 33923;
/** IFD tags. */
private static final Integer SERIES = new Integer(10);
private static final Integer IMAGES = new Integer(15);
private static final Integer DIMDESCR = new Integer(20);
private static final Integer FILTERSET = new Integer(30);
private static final Integer TIMEINFO = new Integer(40);
private static final Integer SCANNERSET = new Integer(50);
private static final Integer EXPERIMENT = new Integer(60);
private static final Integer LUTDESC = new Integer(70);
private static final Hashtable CHANNEL_PRIORITIES = createChannelPriorities();
private static Hashtable createChannelPriorities() {
Hashtable h = new Hashtable();
h.put("red", new Integer(0));
h.put("green", new Integer(1));
h.put("blue", new Integer(2));
h.put("cyan", new Integer(3));
h.put("magenta", new Integer(4));
h.put("yellow", new Integer(5));
h.put("black", new Integer(6));
h.put("gray", new Integer(7));
h.put("", new Integer(8));
return h;
}
// -- Static fields --
private static Hashtable dimensionNames = makeDimensionTable();
// -- Fields --
protected Hashtable[] ifds;
/** Array of IFD-like structures containing metadata. */
protected Hashtable[] headerIFDs;
/** Helper readers. */
protected MinimalTiffReader tiff;
/** Array of image file names. */
protected Vector[] files;
/** Number of series in the file. */
private int numSeries;
/** Name of current LEI file */
private String leiFilename;
private Vector seriesNames;
private Vector seriesDescriptions;
private int lastPlane = 0;
private float[][] physicalSizes;
private int[][] channelMap;
// -- Constructor --
/** Constructs a new Leica reader. */
public LeicaReader() {
super("Leica", new String[] {"lei", "tif", "tiff"});
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, LEI_SUFFIX)) return true;
if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES)) return false;
if (!open) return false; // not allowed to touch the file system
// check for that there is an .lei file in the same directory
String prefix = name;
if (prefix.indexOf(".") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf("_") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists()) lei = new Location(prefix + ".LEI");
}
}
return lei.exists();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessStream) */
public boolean isThisType(RandomAccessStream stream) throws IOException {
if (!FormatTools.validStream(stream, blockCheckLen, false)) return false;
Hashtable ifd = TiffTools.getFirstIFD(stream);
return ifd.containsKey(new Integer(LEICA_MAGIC_TAG));
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
tiff.setId((String) files[series].get(lastPlane));
return tiff.get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
tiff.setId((String) files[series].get(lastPlane));
return tiff.get16BitLookupTable();
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
if (!isRGB()) {
int[] pos = getZCTCoords(no);
pos[1] = indexOf(pos[1], channelMap[series]);
if (pos[1] >= 0) no = getIndex(pos[0], pos[1], pos[2]);
}
lastPlane = no;
tiff.setId((String) files[series].get(no));
return tiff.openBytes(0, buf, x, y, w, h);
}
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
Vector v = new Vector();
v.add(leiFilename);
for (int i=0; i<files.length; i++) {
for (int j=0; j<files[i].size(); j++) {
v.add(files[i].get(j));
}
}
return (String[]) v.toArray(new String[0]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
if (in != null) in.close();
if (tiff != null) tiff.close();
tiff = null;
if (!fileOnly) {
super.close();
leiFilename = null;
files = null;
ifds = headerIFDs = null;
tiff = null;
seriesNames = null;
numSeries = 0;
lastPlane = 0;
channelMap = null;
physicalSizes = null;
seriesDescriptions = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("LeicaReader.initFile(" + id + ")");
close();
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
// need to find the associated .lei file
if (ifds == null) super.initFile(id);
in = new RandomAccessStream(id);
in.order(TiffTools.checkHeader(in).booleanValue());
in.seek(0);
status("Finding companion file name");
// open the TIFF file and look for the "Image Description" field
ifds = TiffTools.getIFDs(in);
if (ifds == null) throw new FormatException("No IFDs found");
String descr = TiffTools.getComment(ifds[0]);
// remove anything of the form "[blah]"
descr = descr.replaceAll("\\[.*.\\]\n", "");
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String lei = id.substring(0, id.lastIndexOf(File.separator) + 1);
StringTokenizer lines = new StringTokenizer(descr, "\n");
String line = null, key = null, value = null;
while (lines.hasMoreTokens()) {
line = lines.nextToken();
if (line.indexOf("=") == -1) continue;
key = line.substring(0, line.indexOf("=")).trim();
value = line.substring(line.indexOf("=") + 1).trim();
addMeta(key, value);
if (key.startsWith("Series Name")) lei += value;
}
// now open the LEI file
Location l = new Location(lei).getAbsoluteFile();
if (l.exists()) {
initFile(lei);
return;
}
else {
l = l.getParentFile();
String[] list = l.list();
for (int i=0; i<list.length; i++) {
if (checkSuffix(list[i], LEI_SUFFIX)) {
initFile(
new Location(l.getAbsolutePath(), list[i]).getAbsolutePath());
return;
}
}
}
throw new FormatException("LEI file not found.");
}
// parse the LEI file
super.initFile(id);
leiFilename = new File(id).exists() ?
new Location(id).getAbsolutePath() : id;
in = new RandomAccessStream(id);
seriesNames = new Vector();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE &&
fourBytes[1] == TiffTools.LITTLE &&
fourBytes[2] == TiffTools.LITTLE &&
fourBytes[3] == TiffTools.LITTLE);
in.order(isLittleEndian());
status("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
Vector v = new Vector();
Hashtable ifd;
while (addr != 0) {
ifd = new Hashtable();
v.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
byte[] data = new byte[size];
in.read(data);
ifd.put(new Integer(tag), data);
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = v.size();
core = new CoreMetadata[numSeries];
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
}
channelMap = new int[numSeries][];
files = new Vector[numSeries];
headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]);
// determine the length of a filename
int nameLength = 0;
int maxPlanes = 0;
status("Parsing metadata blocks");
core[0].littleEndian = !isLittleEndian();
int seriesIndex = 0;
boolean[] valid = new boolean[numSeries];
for (int i=0; i<headerIFDs.length; i++) {
valid[i] = true;
if (headerIFDs[i].get(SERIES) != null) {
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2;
}
Vector f = new Vector();
byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES);
RandomAccessStream data = new RandomAccessStream(tempData);
data.order(isLittleEndian());
int tempImages = data.readInt();
if (((long) tempImages * nameLength) > data.length()) {
data.order(!isLittleEndian());
tempImages = data.readInt();
data.order(isLittleEndian());
}
File dirFile = new File(id).getAbsoluteFile();
String[] listing = null;
String dirPrefix = "";
if (dirFile.exists()) {
listing = dirFile.getParentFile().list();
dirPrefix = dirFile.getParent();
if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator;
}
else {
listing =
(String[]) Location.getIdMap().keySet().toArray(new String[0]);
}
Vector list = new Vector();
for (int k=0; k<listing.length; k++) {
if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) {
list.add(listing[k]);
}
}
boolean tiffsExist = true;
data.seek(20);
String prefix = "";
for (int j=0; j<tempImages; j++) {
// read in each filename
prefix = getString(data, nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location((String) f.get(f.size() - 1));
if (test.exists()) list.remove(prefix);
if (tiffsExist) tiffsExist = test.exists();
}
data.close();
tempData = null;
// at least one of the TIFF files was renamed
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
status("Handling renamed TIFF files");
listing = (String[]) list.toArray(new String[0]);
// grab the file patterns
Vector filePatterns = new Vector();
for (int q=0; q<listing.length; q++) {
Location l = new Location(dirPrefix, listing[q]);
l = l.getAbsoluteFile();
FilePattern pattern = new FilePattern(l);
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
Vector fileList = new Vector();
for (int n=0; n<listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix,
(String[]) fileList.toArray(new String[0]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (int q=0; q<filePatterns.size(); q++) {
String[] pattern =
new FilePattern((String) filePatterns.get(q)).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n=0; n<i; n++) {
if (files[n] == null) continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[i] = new Vector();
for (int n=0; n<pattern.length; n++) {
files[i].add(pattern[n]);
}
}
}
}
}
else files[i] = f;
if (files[i] == null) valid[i] = false;
else {
core[i].imageCount = files[i].size();
if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount;
}
}
int invalidCount = 0;
for (int i=0; i<valid.length; i++) {
if (!valid[i]) invalidCount++;
}
numSeries -= invalidCount;
int[] count = new int[core.length];
for (int i=0; i<core.length; i++) {
count[i] = core[i].imageCount;
}
Vector[] tempFiles = files;
Hashtable[] tempIFDs = headerIFDs;
core = new CoreMetadata[numSeries];
files = new Vector[numSeries];
headerIFDs = new Hashtable[numSeries];
int index = 0;
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
while (!valid[index]) index++;
core[i].imageCount = count[index];
files[i] = tempFiles[index];
Object[] sorted = files[i].toArray();
Arrays.sort(sorted);
files[i].clear();
for (int q=0; q<sorted.length; q++) {
files[i].add(sorted[q]);
}
headerIFDs[i] = tempIFDs[index];
index++;
}
tiff = new MinimalTiffReader();
status("Populating metadata");
if (headerIFDs == null) headerIFDs = ifds;
int fileLength = 0;
int resolution = -1;
String[][] timestamps = new String[headerIFDs.length][];
seriesDescriptions = new Vector();
physicalSizes = new float[headerIFDs.length][5];
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
for (int i=0; i<headerIFDs.length; i++) {
String prefix = "Series " + i + " ";
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
if (temp != null) {
// the series data
// ID_SERIES
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Version", stream.readInt());
addMeta(prefix + "Number of Series", stream.readInt());
fileLength = stream.readInt();
addMeta(prefix + "Length of filename", fileLength);
Integer extLen = new Integer(stream.readInt());
if (extLen.intValue() > fileLength) {
- stream.seek(0);
+ stream.seek(8);
core[0].littleEndian = !isLittleEndian();
stream.order(isLittleEndian());
fileLength = stream.readInt();
extLen = new Integer(stream.readInt());
}
addMeta(prefix + "Length of file extension", extLen);
addMeta(prefix + "Image file extension",
getString(stream, extLen.intValue()));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(IMAGES);
if (temp != null) {
// the image data
// ID_IMAGES
RandomAccessStream s = new RandomAccessStream(temp);
s.order(isLittleEndian());
core[i].imageCount = s.readInt();
core[i].sizeX = s.readInt();
core[i].sizeY = s.readInt();
addMeta(prefix + "Number of images", core[i].imageCount);
addMeta(prefix + "Image width", core[i].sizeX);
addMeta(prefix + "Image height", core[i].sizeY);
addMeta(prefix + "Bits per Sample", s.readInt());
addMeta(prefix + "Samples per pixel", s.readInt());
String p = getString(s, fileLength * 2);
s.close();
StringTokenizer st = new StringTokenizer(p, "_");
StringBuffer buf = new StringBuffer();
st.nextToken();
while (st.hasMoreTokens()) {
String token = st.nextToken();
String lcase = token.toLowerCase();
if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) &&
!lcase.startsWith("ch0") && !lcase.startsWith("c0") &&
!lcase.startsWith("z0"))
{
if (buf.length() > 0) buf.append("_");
buf.append(token);
}
}
seriesNames.add(buf.toString());
}
temp = (byte[]) headerIFDs[i].get(DIMDESCR);
if (temp != null) {
// dimension description
// ID_DIMDESCR
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Voxel Version", stream.readInt());
int voxelType = stream.readInt();
core[i].rgb = voxelType == 20;
addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray");
int bpp = stream.readInt();
addMeta(prefix + "Bytes per pixel", bpp);
switch (bpp) {
case 1:
case 3:
core[i].pixelType = FormatTools.UINT8;
break;
case 2:
case 6:
core[i].pixelType = FormatTools.UINT16;
break;
case 4:
core[i].pixelType = FormatTools.UINT32;
break;
default:
throw new FormatException("Unsupported bytes per pixel (" +
bpp + ")");
}
core[i].dimensionOrder = "XY";
resolution = stream.readInt();
addMeta(prefix + "Real world resolution", resolution);
int length = stream.readInt() * 2;
addMeta(prefix + "Maximum voxel intensity", getString(stream, length));
length = stream.readInt() * 2;
addMeta(prefix + "Minimum voxel intensity", getString(stream, length));
length = stream.readInt();
stream.skipBytes(length * 2);
stream.skipBytes(4); // version number
length = stream.readInt();
for (int j=0; j<length; j++) {
int dimId = stream.readInt();
String dimType = (String) dimensionNames.get(new Integer(dimId));
if (dimType == null) dimType = "";
int size = stream.readInt();
int distance = stream.readInt();
int strlen = stream.readInt();
String physicalSize = getString(stream, strlen * 2);
String unit = "";
if (physicalSize.indexOf(" ") != -1) {
unit = physicalSize.substring(physicalSize.indexOf(" ") + 1);
physicalSize = physicalSize.substring(0, physicalSize.indexOf(" "));
}
float physical = Float.parseFloat(physicalSize) / size;
if (unit.equals("m")) {
physical *= 1000000;
}
if (dimType.equals("x")) {
core[i].sizeX = size;
physicalSizes[i][0] = physical;
}
else if (dimType.equals("y")) {
core[i].sizeY = size;
physicalSizes[i][1] = physical;
}
else if (dimType.indexOf("z") != -1) {
core[i].sizeZ = size;
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
physicalSizes[i][2] = physical;
}
else if (dimType.equals("channel")) {
core[i].sizeC = size;
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
physicalSizes[i][3] = physical;
}
else {
core[i].sizeT = size;
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
physicalSizes[i][4] = physical;
}
addMeta(prefix + "Dim" + j + " type", dimType);
addMeta(prefix + "Dim" + j + " size", size);
addMeta(prefix + "Dim" + j + " distance between sub-dimensions",
distance);
addMeta(prefix + "Dim" + j + " physical length",
physicalSize + " " + unit);
int len = stream.readInt();
addMeta(prefix + "Dim" + j + " physical origin",
getString(stream, len * 2));
}
int len = stream.readInt();
addMeta(prefix + "Series name", getString(stream, len));
len = stream.readInt();
String description = getString(stream, len);
seriesDescriptions.add(description);
addMeta(prefix + "Series description", description);
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i);
temp = (byte[]) headerIFDs[i].get(TIMEINFO);
if (temp != null) {
// time data
// ID_TIMEINFO
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(0);
int nDims = stream.readInt();
addMeta(prefix + "Number of time-stamped dimensions", nDims);
addMeta(prefix + "Time-stamped dimension", stream.readInt());
for (int j=0; j < nDims; j++) {
addMeta(prefix + "Dimension " + j + " ID", stream.readInt());
addMeta(prefix + "Dimension " + j + " size", stream.readInt());
addMeta(prefix + "Dimension " + j + " distance between dimensions",
stream.readInt());
}
int numStamps = stream.readInt();
addMeta(prefix + "Number of time-stamps", numStamps);
timestamps[i] = new String[numStamps];
for (int j=0; j<numStamps; j++) {
timestamps[i][j] = getString(stream, 64);
addMeta(prefix + "Timestamp " + j, timestamps[i][j]);
}
if (stream.getFilePointer() < stream.length()) {
int numTMs = stream.readInt();
addMeta(prefix + "Number of time-markers", numTMs);
for (int j=0; j<numTMs; j++) {
int numDims = stream.readInt();
String time = "Time-marker " + j + " Dimension ";
for (int k=0; k<numDims; k++) {
addMeta(prefix + time + k + " coordinate", stream.readInt());
}
addMeta(prefix + "Time-marker " + j, getString(stream, 64));
}
}
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i);
temp = (byte[]) headerIFDs[i].get(EXPERIMENT);
if (temp != null) {
// experiment data
// ID_EXPERIMENT
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(8);
int len = stream.readInt();
String description = getString(stream, len * 2);
addMeta(prefix + "Image Description", description);
len = stream.readInt();
addMeta(prefix + "Main file extension", getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image format identifier",
getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image extension", getString(stream, len * 2));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(LUTDESC);
if (temp != null) {
// LUT data
// ID_LUTDESC
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
int nChannels = stream.readInt();
if (nChannels > 0) core[i].indexed = true;
addMeta(prefix + "Number of LUT channels", nChannels);
addMeta(prefix + "ID of colored dimension", stream.readInt());
channelMap[i] = new int[nChannels];
String[] luts = new String[nChannels];
for (int j=0; j<nChannels; j++) {
String p = "LUT Channel " + j;
addMeta(prefix + p + " version", stream.readInt());
addMeta(prefix + p + " inverted?", stream.read() == 1);
int length = stream.readInt();
addMeta(prefix + p + " description", getString(stream, length));
length = stream.readInt();
addMeta(prefix + p + " filename", getString(stream, length));
length = stream.readInt();
luts[j] = getString(stream, length);
addMeta(prefix + p + " name", luts[j]);
luts[j] = luts[j].toLowerCase();
stream.skipBytes(8);
}
stream.close();
// finish setting up channel mapping
for (int q=0; q<channelMap[i].length; q++) {
if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = "";
channelMap[i][q] =
((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue();
}
int[] sorted = new int[channelMap[i].length];
Arrays.fill(sorted, -1);
for (int q=0; q<sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n=0; n<channelMap[i].length; n++) {
if (channelMap[i][n] < min && !containsValue(sorted, n)) {
min = channelMap[i][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
for (int q=0; q<channelMap[i].length; q++) {
channelMap[i][sorted[q]] = q;
}
}
core[i].orderCertain = true;
core[i].littleEndian = isLittleEndian();
core[i].falseColor = true;
core[i].metadataComplete = true;
core[i].interleaved = false;
}
for (int i=0; i<numSeries; i++) {
setSeries(i);
if (getSizeZ() == 0) core[i].sizeZ = 1;
if (getSizeT() == 0) core[i].sizeT = 1;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getImageCount() == 0) core[i].imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
core[i].sizeZ = 1;
core[i].sizeT = 1;
}
tiff.setId((String) files[i].get(0));
core[i].sizeX = tiff.getSizeX();
core[i].sizeY = tiff.getSizeY();
core[i].rgb = tiff.isRGB();
core[i].indexed = tiff.isIndexed();
core[i].sizeC *= tiff.getSizeC();
if (getDimensionOrder().indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (getDimensionOrder().indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (getDimensionOrder().indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null &&
timestamps[i].length > 0)
{
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][0], new ParsePosition(0));
firstPlane = date.getTime();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
store.setImageCreationDate(fmt.format(date), i);
}
else {
MetadataTools.setDefaultCreationDate(store, id, i);
}
store.setImageName((String) seriesNames.get(i), i);
store.setImageDescription((String) seriesDescriptions.get(i), i);
store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0);
store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0);
store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0);
store.setDimensionsWaveIncrement(
new Integer((int) physicalSizes[i][3]), i, 0);
store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0);
for (int j=0; j<core[i].imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][j], new ParsePosition(0));
float elapsedTime = (float) (date.getTime() - firstPlane) / 1000;
store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j);
}
}
}
MetadataTools.populatePixels(store, this, true);
setSeries(0);
}
// -- Helper methods --
private void parseInstrumentData(byte[] temp, MetadataStore store, int series)
throws IOException
{
if (temp == null) return;
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(0);
// read 24 byte SAFEARRAY
stream.skipBytes(4);
int cbElements = stream.readInt();
stream.skipBytes(8);
int nElements = stream.readInt();
stream.skipBytes(4);
for (int j=0; j<nElements; j++) {
stream.seek(24 + j * cbElements);
String contentID = getString(stream, 128);
String description = getString(stream, 64);
String data = getString(stream, 64);
int dataType = stream.readShort();
stream.skipBytes(6);
// read data
switch (dataType) {
case 2:
data = String.valueOf(stream.readShort());
stream.skipBytes(6);
break;
case 3:
data = String.valueOf(stream.readInt());
stream.skipBytes(4);
break;
case 4:
data = String.valueOf(stream.readFloat());
stream.skipBytes(4);
break;
case 5:
data = String.valueOf(stream.readDouble());
break;
case 7:
case 11:
int b = stream.read();
stream.skipBytes(7);
data = b == 0 ? "false" : "true";
break;
case 17:
data = stream.readString(1);
stream.skipBytes(7);
break;
default:
stream.skipBytes(8);
}
String[] tokens = contentID.split("\\|");
if (tokens[0].startsWith("CDetectionUnit")) {
// detector information
if (tokens[1].startsWith("PMT")) {
try {
int ndx = tokens[1].lastIndexOf(" ") + 1;
int detector = Integer.parseInt(tokens[1].substring(ndx)) - 1;
if (tokens[2].equals("VideoOffset")) {
store.setDetectorOffset(new Float(data), 0, detector);
}
else if (tokens[2].equals("HighVoltage")) {
store.setDetectorVoltage(new Float(data), 0, detector);
}
}
catch (NumberFormatException e) {
if (debug) LogTools.trace(e);
}
}
}
else if (tokens[0].startsWith("CTurret")) {
// objective information
int objective = Integer.parseInt(tokens[3]);
if (tokens[2].equals("NumericalAperture")) {
store.setObjectiveLensNA(new Float(data), 0, objective);
}
else if (tokens[2].equals("Objective")) {
store.setObjectiveModel(data, 0, objective);
}
else if (tokens[2].equals("OrderNumber")) {
store.setObjectiveSerialNumber(data, 0, objective);
}
}
else if (tokens[0].startsWith("CSpectrophotometerUnit")) {
int ndx = tokens[1].lastIndexOf(" ") + 1;
int channel = Integer.parseInt(tokens[1].substring(ndx)) - 1;
if (tokens[2].equals("Wavelength")) {
Integer wavelength = new Integer((int) Float.parseFloat(data));
if (tokens[3].equals("0")) {
store.setLogicalChannelEmWave(wavelength, series, channel);
}
else if (tokens[3].equals("1")) {
store.setLogicalChannelExWave(wavelength, series, channel);
}
}
else if (tokens[2].equals("Stain")) {
store.setLogicalChannelName(data, series, channel);
}
}
else if (tokens[0].startsWith("CXYZStage")) {
if (tokens[2].equals("XPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setStagePositionPositionX(new Float(data), series, 0, q);
}
}
else if (tokens[2].equals("YPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setStagePositionPositionY(new Float(data), series, 0, q);
}
}
else if (tokens[2].equals("ZPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setStagePositionPositionZ(new Float(data), series, 0, q);
}
}
}
if (contentID.equals("dblVoxelX")) {
physicalSizes[series][0] = Float.parseFloat(data);
}
else if (contentID.equals("dblVoxelY")) {
physicalSizes[series][1] = Float.parseFloat(data);
}
else if (contentID.equals("dblVoxelZ")) {
physicalSizes[series][2] = Float.parseFloat(data);
}
addMeta("Series " + series + " " + contentID, data);
stream.skipBytes(16);
}
stream.close();
}
private boolean usedFile(String s) {
if (files == null) return false;
for (int i=0; i<files.length; i++) {
if (files[i] == null) continue;
for (int j=0; j<files[i].size(); j++) {
if (((String) files[i].get(j)).endsWith(s)) return true;
}
}
return false;
}
private String getString(RandomAccessStream stream, int len)
throws IOException
{
return DataTools.stripString(stream.readString(len));
}
private boolean containsValue(int[] array, int value) {
return indexOf(value, array) != -1;
}
private int indexOf(int value, int[] array) {
for (int i=0; i<array.length; i++) {
if (array[i] == value) return i;
}
return -1;
}
private static Hashtable makeDimensionTable() {
Hashtable table = new Hashtable();
table.put(new Integer(0), "undefined");
table.put(new Integer(120), "x");
table.put(new Integer(121), "y");
table.put(new Integer(122), "z");
table.put(new Integer(116), "t");
table.put(new Integer(6815843), "channel");
table.put(new Integer(6357100), "wave length");
table.put(new Integer(7602290), "rotation");
table.put(new Integer(7798904), "x-wide for the motorized xy-stage");
table.put(new Integer(7798905), "y-wide for the motorized xy-stage");
table.put(new Integer(7798906), "z-wide for the z-stage-drive");
table.put(new Integer(4259957), "user1 - unspecified");
table.put(new Integer(4325493), "user2 - unspecified");
table.put(new Integer(4391029), "user3 - unspecified");
table.put(new Integer(6357095), "graylevel");
table.put(new Integer(6422631), "graylevel1");
table.put(new Integer(6488167), "graylevel2");
table.put(new Integer(6553703), "graylevel3");
table.put(new Integer(7864398), "logical x");
table.put(new Integer(7929934), "logical y");
table.put(new Integer(7995470), "logical z");
table.put(new Integer(7602254), "logical t");
table.put(new Integer(7077966), "logical lambda");
table.put(new Integer(7471182), "logical rotation");
table.put(new Integer(5767246), "logical x-wide");
table.put(new Integer(5832782), "logical y-wide");
table.put(new Integer(5898318), "logical z-wide");
return table;
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("LeicaReader.initFile(" + id + ")");
close();
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
// need to find the associated .lei file
if (ifds == null) super.initFile(id);
in = new RandomAccessStream(id);
in.order(TiffTools.checkHeader(in).booleanValue());
in.seek(0);
status("Finding companion file name");
// open the TIFF file and look for the "Image Description" field
ifds = TiffTools.getIFDs(in);
if (ifds == null) throw new FormatException("No IFDs found");
String descr = TiffTools.getComment(ifds[0]);
// remove anything of the form "[blah]"
descr = descr.replaceAll("\\[.*.\\]\n", "");
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String lei = id.substring(0, id.lastIndexOf(File.separator) + 1);
StringTokenizer lines = new StringTokenizer(descr, "\n");
String line = null, key = null, value = null;
while (lines.hasMoreTokens()) {
line = lines.nextToken();
if (line.indexOf("=") == -1) continue;
key = line.substring(0, line.indexOf("=")).trim();
value = line.substring(line.indexOf("=") + 1).trim();
addMeta(key, value);
if (key.startsWith("Series Name")) lei += value;
}
// now open the LEI file
Location l = new Location(lei).getAbsoluteFile();
if (l.exists()) {
initFile(lei);
return;
}
else {
l = l.getParentFile();
String[] list = l.list();
for (int i=0; i<list.length; i++) {
if (checkSuffix(list[i], LEI_SUFFIX)) {
initFile(
new Location(l.getAbsolutePath(), list[i]).getAbsolutePath());
return;
}
}
}
throw new FormatException("LEI file not found.");
}
// parse the LEI file
super.initFile(id);
leiFilename = new File(id).exists() ?
new Location(id).getAbsolutePath() : id;
in = new RandomAccessStream(id);
seriesNames = new Vector();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE &&
fourBytes[1] == TiffTools.LITTLE &&
fourBytes[2] == TiffTools.LITTLE &&
fourBytes[3] == TiffTools.LITTLE);
in.order(isLittleEndian());
status("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
Vector v = new Vector();
Hashtable ifd;
while (addr != 0) {
ifd = new Hashtable();
v.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
byte[] data = new byte[size];
in.read(data);
ifd.put(new Integer(tag), data);
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = v.size();
core = new CoreMetadata[numSeries];
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
}
channelMap = new int[numSeries][];
files = new Vector[numSeries];
headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]);
// determine the length of a filename
int nameLength = 0;
int maxPlanes = 0;
status("Parsing metadata blocks");
core[0].littleEndian = !isLittleEndian();
int seriesIndex = 0;
boolean[] valid = new boolean[numSeries];
for (int i=0; i<headerIFDs.length; i++) {
valid[i] = true;
if (headerIFDs[i].get(SERIES) != null) {
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2;
}
Vector f = new Vector();
byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES);
RandomAccessStream data = new RandomAccessStream(tempData);
data.order(isLittleEndian());
int tempImages = data.readInt();
if (((long) tempImages * nameLength) > data.length()) {
data.order(!isLittleEndian());
tempImages = data.readInt();
data.order(isLittleEndian());
}
File dirFile = new File(id).getAbsoluteFile();
String[] listing = null;
String dirPrefix = "";
if (dirFile.exists()) {
listing = dirFile.getParentFile().list();
dirPrefix = dirFile.getParent();
if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator;
}
else {
listing =
(String[]) Location.getIdMap().keySet().toArray(new String[0]);
}
Vector list = new Vector();
for (int k=0; k<listing.length; k++) {
if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) {
list.add(listing[k]);
}
}
boolean tiffsExist = true;
data.seek(20);
String prefix = "";
for (int j=0; j<tempImages; j++) {
// read in each filename
prefix = getString(data, nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location((String) f.get(f.size() - 1));
if (test.exists()) list.remove(prefix);
if (tiffsExist) tiffsExist = test.exists();
}
data.close();
tempData = null;
// at least one of the TIFF files was renamed
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
status("Handling renamed TIFF files");
listing = (String[]) list.toArray(new String[0]);
// grab the file patterns
Vector filePatterns = new Vector();
for (int q=0; q<listing.length; q++) {
Location l = new Location(dirPrefix, listing[q]);
l = l.getAbsoluteFile();
FilePattern pattern = new FilePattern(l);
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
Vector fileList = new Vector();
for (int n=0; n<listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix,
(String[]) fileList.toArray(new String[0]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (int q=0; q<filePatterns.size(); q++) {
String[] pattern =
new FilePattern((String) filePatterns.get(q)).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n=0; n<i; n++) {
if (files[n] == null) continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[i] = new Vector();
for (int n=0; n<pattern.length; n++) {
files[i].add(pattern[n]);
}
}
}
}
}
else files[i] = f;
if (files[i] == null) valid[i] = false;
else {
core[i].imageCount = files[i].size();
if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount;
}
}
int invalidCount = 0;
for (int i=0; i<valid.length; i++) {
if (!valid[i]) invalidCount++;
}
numSeries -= invalidCount;
int[] count = new int[core.length];
for (int i=0; i<core.length; i++) {
count[i] = core[i].imageCount;
}
Vector[] tempFiles = files;
Hashtable[] tempIFDs = headerIFDs;
core = new CoreMetadata[numSeries];
files = new Vector[numSeries];
headerIFDs = new Hashtable[numSeries];
int index = 0;
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
while (!valid[index]) index++;
core[i].imageCount = count[index];
files[i] = tempFiles[index];
Object[] sorted = files[i].toArray();
Arrays.sort(sorted);
files[i].clear();
for (int q=0; q<sorted.length; q++) {
files[i].add(sorted[q]);
}
headerIFDs[i] = tempIFDs[index];
index++;
}
tiff = new MinimalTiffReader();
status("Populating metadata");
if (headerIFDs == null) headerIFDs = ifds;
int fileLength = 0;
int resolution = -1;
String[][] timestamps = new String[headerIFDs.length][];
seriesDescriptions = new Vector();
physicalSizes = new float[headerIFDs.length][5];
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
for (int i=0; i<headerIFDs.length; i++) {
String prefix = "Series " + i + " ";
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
if (temp != null) {
// the series data
// ID_SERIES
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Version", stream.readInt());
addMeta(prefix + "Number of Series", stream.readInt());
fileLength = stream.readInt();
addMeta(prefix + "Length of filename", fileLength);
Integer extLen = new Integer(stream.readInt());
if (extLen.intValue() > fileLength) {
stream.seek(0);
core[0].littleEndian = !isLittleEndian();
stream.order(isLittleEndian());
fileLength = stream.readInt();
extLen = new Integer(stream.readInt());
}
addMeta(prefix + "Length of file extension", extLen);
addMeta(prefix + "Image file extension",
getString(stream, extLen.intValue()));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(IMAGES);
if (temp != null) {
// the image data
// ID_IMAGES
RandomAccessStream s = new RandomAccessStream(temp);
s.order(isLittleEndian());
core[i].imageCount = s.readInt();
core[i].sizeX = s.readInt();
core[i].sizeY = s.readInt();
addMeta(prefix + "Number of images", core[i].imageCount);
addMeta(prefix + "Image width", core[i].sizeX);
addMeta(prefix + "Image height", core[i].sizeY);
addMeta(prefix + "Bits per Sample", s.readInt());
addMeta(prefix + "Samples per pixel", s.readInt());
String p = getString(s, fileLength * 2);
s.close();
StringTokenizer st = new StringTokenizer(p, "_");
StringBuffer buf = new StringBuffer();
st.nextToken();
while (st.hasMoreTokens()) {
String token = st.nextToken();
String lcase = token.toLowerCase();
if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) &&
!lcase.startsWith("ch0") && !lcase.startsWith("c0") &&
!lcase.startsWith("z0"))
{
if (buf.length() > 0) buf.append("_");
buf.append(token);
}
}
seriesNames.add(buf.toString());
}
temp = (byte[]) headerIFDs[i].get(DIMDESCR);
if (temp != null) {
// dimension description
// ID_DIMDESCR
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Voxel Version", stream.readInt());
int voxelType = stream.readInt();
core[i].rgb = voxelType == 20;
addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray");
int bpp = stream.readInt();
addMeta(prefix + "Bytes per pixel", bpp);
switch (bpp) {
case 1:
case 3:
core[i].pixelType = FormatTools.UINT8;
break;
case 2:
case 6:
core[i].pixelType = FormatTools.UINT16;
break;
case 4:
core[i].pixelType = FormatTools.UINT32;
break;
default:
throw new FormatException("Unsupported bytes per pixel (" +
bpp + ")");
}
core[i].dimensionOrder = "XY";
resolution = stream.readInt();
addMeta(prefix + "Real world resolution", resolution);
int length = stream.readInt() * 2;
addMeta(prefix + "Maximum voxel intensity", getString(stream, length));
length = stream.readInt() * 2;
addMeta(prefix + "Minimum voxel intensity", getString(stream, length));
length = stream.readInt();
stream.skipBytes(length * 2);
stream.skipBytes(4); // version number
length = stream.readInt();
for (int j=0; j<length; j++) {
int dimId = stream.readInt();
String dimType = (String) dimensionNames.get(new Integer(dimId));
if (dimType == null) dimType = "";
int size = stream.readInt();
int distance = stream.readInt();
int strlen = stream.readInt();
String physicalSize = getString(stream, strlen * 2);
String unit = "";
if (physicalSize.indexOf(" ") != -1) {
unit = physicalSize.substring(physicalSize.indexOf(" ") + 1);
physicalSize = physicalSize.substring(0, physicalSize.indexOf(" "));
}
float physical = Float.parseFloat(physicalSize) / size;
if (unit.equals("m")) {
physical *= 1000000;
}
if (dimType.equals("x")) {
core[i].sizeX = size;
physicalSizes[i][0] = physical;
}
else if (dimType.equals("y")) {
core[i].sizeY = size;
physicalSizes[i][1] = physical;
}
else if (dimType.indexOf("z") != -1) {
core[i].sizeZ = size;
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
physicalSizes[i][2] = physical;
}
else if (dimType.equals("channel")) {
core[i].sizeC = size;
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
physicalSizes[i][3] = physical;
}
else {
core[i].sizeT = size;
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
physicalSizes[i][4] = physical;
}
addMeta(prefix + "Dim" + j + " type", dimType);
addMeta(prefix + "Dim" + j + " size", size);
addMeta(prefix + "Dim" + j + " distance between sub-dimensions",
distance);
addMeta(prefix + "Dim" + j + " physical length",
physicalSize + " " + unit);
int len = stream.readInt();
addMeta(prefix + "Dim" + j + " physical origin",
getString(stream, len * 2));
}
int len = stream.readInt();
addMeta(prefix + "Series name", getString(stream, len));
len = stream.readInt();
String description = getString(stream, len);
seriesDescriptions.add(description);
addMeta(prefix + "Series description", description);
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i);
temp = (byte[]) headerIFDs[i].get(TIMEINFO);
if (temp != null) {
// time data
// ID_TIMEINFO
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(0);
int nDims = stream.readInt();
addMeta(prefix + "Number of time-stamped dimensions", nDims);
addMeta(prefix + "Time-stamped dimension", stream.readInt());
for (int j=0; j < nDims; j++) {
addMeta(prefix + "Dimension " + j + " ID", stream.readInt());
addMeta(prefix + "Dimension " + j + " size", stream.readInt());
addMeta(prefix + "Dimension " + j + " distance between dimensions",
stream.readInt());
}
int numStamps = stream.readInt();
addMeta(prefix + "Number of time-stamps", numStamps);
timestamps[i] = new String[numStamps];
for (int j=0; j<numStamps; j++) {
timestamps[i][j] = getString(stream, 64);
addMeta(prefix + "Timestamp " + j, timestamps[i][j]);
}
if (stream.getFilePointer() < stream.length()) {
int numTMs = stream.readInt();
addMeta(prefix + "Number of time-markers", numTMs);
for (int j=0; j<numTMs; j++) {
int numDims = stream.readInt();
String time = "Time-marker " + j + " Dimension ";
for (int k=0; k<numDims; k++) {
addMeta(prefix + time + k + " coordinate", stream.readInt());
}
addMeta(prefix + "Time-marker " + j, getString(stream, 64));
}
}
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i);
temp = (byte[]) headerIFDs[i].get(EXPERIMENT);
if (temp != null) {
// experiment data
// ID_EXPERIMENT
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(8);
int len = stream.readInt();
String description = getString(stream, len * 2);
addMeta(prefix + "Image Description", description);
len = stream.readInt();
addMeta(prefix + "Main file extension", getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image format identifier",
getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image extension", getString(stream, len * 2));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(LUTDESC);
if (temp != null) {
// LUT data
// ID_LUTDESC
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
int nChannels = stream.readInt();
if (nChannels > 0) core[i].indexed = true;
addMeta(prefix + "Number of LUT channels", nChannels);
addMeta(prefix + "ID of colored dimension", stream.readInt());
channelMap[i] = new int[nChannels];
String[] luts = new String[nChannels];
for (int j=0; j<nChannels; j++) {
String p = "LUT Channel " + j;
addMeta(prefix + p + " version", stream.readInt());
addMeta(prefix + p + " inverted?", stream.read() == 1);
int length = stream.readInt();
addMeta(prefix + p + " description", getString(stream, length));
length = stream.readInt();
addMeta(prefix + p + " filename", getString(stream, length));
length = stream.readInt();
luts[j] = getString(stream, length);
addMeta(prefix + p + " name", luts[j]);
luts[j] = luts[j].toLowerCase();
stream.skipBytes(8);
}
stream.close();
// finish setting up channel mapping
for (int q=0; q<channelMap[i].length; q++) {
if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = "";
channelMap[i][q] =
((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue();
}
int[] sorted = new int[channelMap[i].length];
Arrays.fill(sorted, -1);
for (int q=0; q<sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n=0; n<channelMap[i].length; n++) {
if (channelMap[i][n] < min && !containsValue(sorted, n)) {
min = channelMap[i][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
for (int q=0; q<channelMap[i].length; q++) {
channelMap[i][sorted[q]] = q;
}
}
core[i].orderCertain = true;
core[i].littleEndian = isLittleEndian();
core[i].falseColor = true;
core[i].metadataComplete = true;
core[i].interleaved = false;
}
for (int i=0; i<numSeries; i++) {
setSeries(i);
if (getSizeZ() == 0) core[i].sizeZ = 1;
if (getSizeT() == 0) core[i].sizeT = 1;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getImageCount() == 0) core[i].imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
core[i].sizeZ = 1;
core[i].sizeT = 1;
}
tiff.setId((String) files[i].get(0));
core[i].sizeX = tiff.getSizeX();
core[i].sizeY = tiff.getSizeY();
core[i].rgb = tiff.isRGB();
core[i].indexed = tiff.isIndexed();
core[i].sizeC *= tiff.getSizeC();
if (getDimensionOrder().indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (getDimensionOrder().indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (getDimensionOrder().indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null &&
timestamps[i].length > 0)
{
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][0], new ParsePosition(0));
firstPlane = date.getTime();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
store.setImageCreationDate(fmt.format(date), i);
}
else {
MetadataTools.setDefaultCreationDate(store, id, i);
}
store.setImageName((String) seriesNames.get(i), i);
store.setImageDescription((String) seriesDescriptions.get(i), i);
store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0);
store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0);
store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0);
store.setDimensionsWaveIncrement(
new Integer((int) physicalSizes[i][3]), i, 0);
store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0);
for (int j=0; j<core[i].imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][j], new ParsePosition(0));
float elapsedTime = (float) (date.getTime() - firstPlane) / 1000;
store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j);
}
}
}
MetadataTools.populatePixels(store, this, true);
setSeries(0);
}
| protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("LeicaReader.initFile(" + id + ")");
close();
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
// need to find the associated .lei file
if (ifds == null) super.initFile(id);
in = new RandomAccessStream(id);
in.order(TiffTools.checkHeader(in).booleanValue());
in.seek(0);
status("Finding companion file name");
// open the TIFF file and look for the "Image Description" field
ifds = TiffTools.getIFDs(in);
if (ifds == null) throw new FormatException("No IFDs found");
String descr = TiffTools.getComment(ifds[0]);
// remove anything of the form "[blah]"
descr = descr.replaceAll("\\[.*.\\]\n", "");
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String lei = id.substring(0, id.lastIndexOf(File.separator) + 1);
StringTokenizer lines = new StringTokenizer(descr, "\n");
String line = null, key = null, value = null;
while (lines.hasMoreTokens()) {
line = lines.nextToken();
if (line.indexOf("=") == -1) continue;
key = line.substring(0, line.indexOf("=")).trim();
value = line.substring(line.indexOf("=") + 1).trim();
addMeta(key, value);
if (key.startsWith("Series Name")) lei += value;
}
// now open the LEI file
Location l = new Location(lei).getAbsoluteFile();
if (l.exists()) {
initFile(lei);
return;
}
else {
l = l.getParentFile();
String[] list = l.list();
for (int i=0; i<list.length; i++) {
if (checkSuffix(list[i], LEI_SUFFIX)) {
initFile(
new Location(l.getAbsolutePath(), list[i]).getAbsolutePath());
return;
}
}
}
throw new FormatException("LEI file not found.");
}
// parse the LEI file
super.initFile(id);
leiFilename = new File(id).exists() ?
new Location(id).getAbsolutePath() : id;
in = new RandomAccessStream(id);
seriesNames = new Vector();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE &&
fourBytes[1] == TiffTools.LITTLE &&
fourBytes[2] == TiffTools.LITTLE &&
fourBytes[3] == TiffTools.LITTLE);
in.order(isLittleEndian());
status("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
Vector v = new Vector();
Hashtable ifd;
while (addr != 0) {
ifd = new Hashtable();
v.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
byte[] data = new byte[size];
in.read(data);
ifd.put(new Integer(tag), data);
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = v.size();
core = new CoreMetadata[numSeries];
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
}
channelMap = new int[numSeries][];
files = new Vector[numSeries];
headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]);
// determine the length of a filename
int nameLength = 0;
int maxPlanes = 0;
status("Parsing metadata blocks");
core[0].littleEndian = !isLittleEndian();
int seriesIndex = 0;
boolean[] valid = new boolean[numSeries];
for (int i=0; i<headerIFDs.length; i++) {
valid[i] = true;
if (headerIFDs[i].get(SERIES) != null) {
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2;
}
Vector f = new Vector();
byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES);
RandomAccessStream data = new RandomAccessStream(tempData);
data.order(isLittleEndian());
int tempImages = data.readInt();
if (((long) tempImages * nameLength) > data.length()) {
data.order(!isLittleEndian());
tempImages = data.readInt();
data.order(isLittleEndian());
}
File dirFile = new File(id).getAbsoluteFile();
String[] listing = null;
String dirPrefix = "";
if (dirFile.exists()) {
listing = dirFile.getParentFile().list();
dirPrefix = dirFile.getParent();
if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator;
}
else {
listing =
(String[]) Location.getIdMap().keySet().toArray(new String[0]);
}
Vector list = new Vector();
for (int k=0; k<listing.length; k++) {
if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) {
list.add(listing[k]);
}
}
boolean tiffsExist = true;
data.seek(20);
String prefix = "";
for (int j=0; j<tempImages; j++) {
// read in each filename
prefix = getString(data, nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location((String) f.get(f.size() - 1));
if (test.exists()) list.remove(prefix);
if (tiffsExist) tiffsExist = test.exists();
}
data.close();
tempData = null;
// at least one of the TIFF files was renamed
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
status("Handling renamed TIFF files");
listing = (String[]) list.toArray(new String[0]);
// grab the file patterns
Vector filePatterns = new Vector();
for (int q=0; q<listing.length; q++) {
Location l = new Location(dirPrefix, listing[q]);
l = l.getAbsoluteFile();
FilePattern pattern = new FilePattern(l);
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
Vector fileList = new Vector();
for (int n=0; n<listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix,
(String[]) fileList.toArray(new String[0]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (int q=0; q<filePatterns.size(); q++) {
String[] pattern =
new FilePattern((String) filePatterns.get(q)).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n=0; n<i; n++) {
if (files[n] == null) continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[i] = new Vector();
for (int n=0; n<pattern.length; n++) {
files[i].add(pattern[n]);
}
}
}
}
}
else files[i] = f;
if (files[i] == null) valid[i] = false;
else {
core[i].imageCount = files[i].size();
if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount;
}
}
int invalidCount = 0;
for (int i=0; i<valid.length; i++) {
if (!valid[i]) invalidCount++;
}
numSeries -= invalidCount;
int[] count = new int[core.length];
for (int i=0; i<core.length; i++) {
count[i] = core[i].imageCount;
}
Vector[] tempFiles = files;
Hashtable[] tempIFDs = headerIFDs;
core = new CoreMetadata[numSeries];
files = new Vector[numSeries];
headerIFDs = new Hashtable[numSeries];
int index = 0;
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
while (!valid[index]) index++;
core[i].imageCount = count[index];
files[i] = tempFiles[index];
Object[] sorted = files[i].toArray();
Arrays.sort(sorted);
files[i].clear();
for (int q=0; q<sorted.length; q++) {
files[i].add(sorted[q]);
}
headerIFDs[i] = tempIFDs[index];
index++;
}
tiff = new MinimalTiffReader();
status("Populating metadata");
if (headerIFDs == null) headerIFDs = ifds;
int fileLength = 0;
int resolution = -1;
String[][] timestamps = new String[headerIFDs.length][];
seriesDescriptions = new Vector();
physicalSizes = new float[headerIFDs.length][5];
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
for (int i=0; i<headerIFDs.length; i++) {
String prefix = "Series " + i + " ";
byte[] temp = (byte[]) headerIFDs[i].get(SERIES);
if (temp != null) {
// the series data
// ID_SERIES
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Version", stream.readInt());
addMeta(prefix + "Number of Series", stream.readInt());
fileLength = stream.readInt();
addMeta(prefix + "Length of filename", fileLength);
Integer extLen = new Integer(stream.readInt());
if (extLen.intValue() > fileLength) {
stream.seek(8);
core[0].littleEndian = !isLittleEndian();
stream.order(isLittleEndian());
fileLength = stream.readInt();
extLen = new Integer(stream.readInt());
}
addMeta(prefix + "Length of file extension", extLen);
addMeta(prefix + "Image file extension",
getString(stream, extLen.intValue()));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(IMAGES);
if (temp != null) {
// the image data
// ID_IMAGES
RandomAccessStream s = new RandomAccessStream(temp);
s.order(isLittleEndian());
core[i].imageCount = s.readInt();
core[i].sizeX = s.readInt();
core[i].sizeY = s.readInt();
addMeta(prefix + "Number of images", core[i].imageCount);
addMeta(prefix + "Image width", core[i].sizeX);
addMeta(prefix + "Image height", core[i].sizeY);
addMeta(prefix + "Bits per Sample", s.readInt());
addMeta(prefix + "Samples per pixel", s.readInt());
String p = getString(s, fileLength * 2);
s.close();
StringTokenizer st = new StringTokenizer(p, "_");
StringBuffer buf = new StringBuffer();
st.nextToken();
while (st.hasMoreTokens()) {
String token = st.nextToken();
String lcase = token.toLowerCase();
if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) &&
!lcase.startsWith("ch0") && !lcase.startsWith("c0") &&
!lcase.startsWith("z0"))
{
if (buf.length() > 0) buf.append("_");
buf.append(token);
}
}
seriesNames.add(buf.toString());
}
temp = (byte[]) headerIFDs[i].get(DIMDESCR);
if (temp != null) {
// dimension description
// ID_DIMDESCR
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
addMeta(prefix + "Voxel Version", stream.readInt());
int voxelType = stream.readInt();
core[i].rgb = voxelType == 20;
addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray");
int bpp = stream.readInt();
addMeta(prefix + "Bytes per pixel", bpp);
switch (bpp) {
case 1:
case 3:
core[i].pixelType = FormatTools.UINT8;
break;
case 2:
case 6:
core[i].pixelType = FormatTools.UINT16;
break;
case 4:
core[i].pixelType = FormatTools.UINT32;
break;
default:
throw new FormatException("Unsupported bytes per pixel (" +
bpp + ")");
}
core[i].dimensionOrder = "XY";
resolution = stream.readInt();
addMeta(prefix + "Real world resolution", resolution);
int length = stream.readInt() * 2;
addMeta(prefix + "Maximum voxel intensity", getString(stream, length));
length = stream.readInt() * 2;
addMeta(prefix + "Minimum voxel intensity", getString(stream, length));
length = stream.readInt();
stream.skipBytes(length * 2);
stream.skipBytes(4); // version number
length = stream.readInt();
for (int j=0; j<length; j++) {
int dimId = stream.readInt();
String dimType = (String) dimensionNames.get(new Integer(dimId));
if (dimType == null) dimType = "";
int size = stream.readInt();
int distance = stream.readInt();
int strlen = stream.readInt();
String physicalSize = getString(stream, strlen * 2);
String unit = "";
if (physicalSize.indexOf(" ") != -1) {
unit = physicalSize.substring(physicalSize.indexOf(" ") + 1);
physicalSize = physicalSize.substring(0, physicalSize.indexOf(" "));
}
float physical = Float.parseFloat(physicalSize) / size;
if (unit.equals("m")) {
physical *= 1000000;
}
if (dimType.equals("x")) {
core[i].sizeX = size;
physicalSizes[i][0] = physical;
}
else if (dimType.equals("y")) {
core[i].sizeY = size;
physicalSizes[i][1] = physical;
}
else if (dimType.indexOf("z") != -1) {
core[i].sizeZ = size;
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
physicalSizes[i][2] = physical;
}
else if (dimType.equals("channel")) {
core[i].sizeC = size;
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
physicalSizes[i][3] = physical;
}
else {
core[i].sizeT = size;
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
physicalSizes[i][4] = physical;
}
addMeta(prefix + "Dim" + j + " type", dimType);
addMeta(prefix + "Dim" + j + " size", size);
addMeta(prefix + "Dim" + j + " distance between sub-dimensions",
distance);
addMeta(prefix + "Dim" + j + " physical length",
physicalSize + " " + unit);
int len = stream.readInt();
addMeta(prefix + "Dim" + j + " physical origin",
getString(stream, len * 2));
}
int len = stream.readInt();
addMeta(prefix + "Series name", getString(stream, len));
len = stream.readInt();
String description = getString(stream, len);
seriesDescriptions.add(description);
addMeta(prefix + "Series description", description);
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i);
temp = (byte[]) headerIFDs[i].get(TIMEINFO);
if (temp != null) {
// time data
// ID_TIMEINFO
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(0);
int nDims = stream.readInt();
addMeta(prefix + "Number of time-stamped dimensions", nDims);
addMeta(prefix + "Time-stamped dimension", stream.readInt());
for (int j=0; j < nDims; j++) {
addMeta(prefix + "Dimension " + j + " ID", stream.readInt());
addMeta(prefix + "Dimension " + j + " size", stream.readInt());
addMeta(prefix + "Dimension " + j + " distance between dimensions",
stream.readInt());
}
int numStamps = stream.readInt();
addMeta(prefix + "Number of time-stamps", numStamps);
timestamps[i] = new String[numStamps];
for (int j=0; j<numStamps; j++) {
timestamps[i][j] = getString(stream, 64);
addMeta(prefix + "Timestamp " + j, timestamps[i][j]);
}
if (stream.getFilePointer() < stream.length()) {
int numTMs = stream.readInt();
addMeta(prefix + "Number of time-markers", numTMs);
for (int j=0; j<numTMs; j++) {
int numDims = stream.readInt();
String time = "Time-marker " + j + " Dimension ";
for (int k=0; k<numDims; k++) {
addMeta(prefix + time + k + " coordinate", stream.readInt());
}
addMeta(prefix + "Time-marker " + j, getString(stream, 64));
}
}
stream.close();
}
parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i);
temp = (byte[]) headerIFDs[i].get(EXPERIMENT);
if (temp != null) {
// experiment data
// ID_EXPERIMENT
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
stream.seek(8);
int len = stream.readInt();
String description = getString(stream, len * 2);
addMeta(prefix + "Image Description", description);
len = stream.readInt();
addMeta(prefix + "Main file extension", getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image format identifier",
getString(stream, len * 2));
len = stream.readInt();
addMeta(prefix + "Single image extension", getString(stream, len * 2));
stream.close();
}
temp = (byte[]) headerIFDs[i].get(LUTDESC);
if (temp != null) {
// LUT data
// ID_LUTDESC
RandomAccessStream stream = new RandomAccessStream(temp);
stream.order(isLittleEndian());
int nChannels = stream.readInt();
if (nChannels > 0) core[i].indexed = true;
addMeta(prefix + "Number of LUT channels", nChannels);
addMeta(prefix + "ID of colored dimension", stream.readInt());
channelMap[i] = new int[nChannels];
String[] luts = new String[nChannels];
for (int j=0; j<nChannels; j++) {
String p = "LUT Channel " + j;
addMeta(prefix + p + " version", stream.readInt());
addMeta(prefix + p + " inverted?", stream.read() == 1);
int length = stream.readInt();
addMeta(prefix + p + " description", getString(stream, length));
length = stream.readInt();
addMeta(prefix + p + " filename", getString(stream, length));
length = stream.readInt();
luts[j] = getString(stream, length);
addMeta(prefix + p + " name", luts[j]);
luts[j] = luts[j].toLowerCase();
stream.skipBytes(8);
}
stream.close();
// finish setting up channel mapping
for (int q=0; q<channelMap[i].length; q++) {
if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = "";
channelMap[i][q] =
((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue();
}
int[] sorted = new int[channelMap[i].length];
Arrays.fill(sorted, -1);
for (int q=0; q<sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n=0; n<channelMap[i].length; n++) {
if (channelMap[i][n] < min && !containsValue(sorted, n)) {
min = channelMap[i][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
for (int q=0; q<channelMap[i].length; q++) {
channelMap[i][sorted[q]] = q;
}
}
core[i].orderCertain = true;
core[i].littleEndian = isLittleEndian();
core[i].falseColor = true;
core[i].metadataComplete = true;
core[i].interleaved = false;
}
for (int i=0; i<numSeries; i++) {
setSeries(i);
if (getSizeZ() == 0) core[i].sizeZ = 1;
if (getSizeT() == 0) core[i].sizeT = 1;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getImageCount() == 0) core[i].imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
core[i].sizeZ = 1;
core[i].sizeT = 1;
}
tiff.setId((String) files[i].get(0));
core[i].sizeX = tiff.getSizeX();
core[i].sizeY = tiff.getSizeY();
core[i].rgb = tiff.isRGB();
core[i].indexed = tiff.isIndexed();
core[i].sizeC *= tiff.getSizeC();
if (getDimensionOrder().indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (getDimensionOrder().indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (getDimensionOrder().indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null &&
timestamps[i].length > 0)
{
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][0], new ParsePosition(0));
firstPlane = date.getTime();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
store.setImageCreationDate(fmt.format(date), i);
}
else {
MetadataTools.setDefaultCreationDate(store, id, i);
}
store.setImageName((String) seriesNames.get(i), i);
store.setImageDescription((String) seriesDescriptions.get(i), i);
store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0);
store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0);
store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0);
store.setDimensionsWaveIncrement(
new Integer((int) physicalSizes[i][3]), i, 0);
store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0);
for (int j=0; j<core[i].imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
SimpleDateFormat parse =
new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS");
Date date = parse.parse(timestamps[i][j], new ParsePosition(0));
float elapsedTime = (float) (date.getTime() - firstPlane) / 1000;
store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j);
}
}
}
MetadataTools.populatePixels(store, this, true);
setSeries(0);
}
|
diff --git a/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java b/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java
index 59a6eaa2..4a484f13 100644
--- a/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java
+++ b/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java
@@ -1,193 +1,195 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.spark.component.tabbedPane;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.Default;
import org.jivesoftware.spark.util.log.Log;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.util.StringTokenizer;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicPanelUI;
/**
* Represents a single instance of a Tab Paint Component.
*
* @author Derek DeMoro
*/
public class TabPanelUI extends BasicPanelUI {
private Color backgroundColor1 = new Color(0, 0, 0, 0);
private Color backgroundColor2 = new Color(0, 0, 0, 0);
private Color borderColor = new Color(86, 88, 72);
private Color borderColorAlpha1 = new Color(86, 88, 72, 100);
private Color borderColorAlpha2 = new Color(86, 88, 72, 50);
private Color borderHighlight = new Color(225, 224, 224);
private boolean selected;
private boolean hideBorder;
private int placement = JTabbedPane.TOP;
// ------------------------------------------------------------------------------------------------------------------
// Custom installation methods
// ------------------------------------------------------------------------------------------------------------------
protected void installDefaults(JPanel p) {
p.setOpaque(false);
}
public void setSelected(boolean selected) {
if (selected) {
backgroundColor1 = getSelectedStartColor();
backgroundColor2 = getSelectedEndColor();
}
else {
backgroundColor1 = new Color(0, 0, 0, 0);
backgroundColor2 = new Color(0, 0, 0, 0);
}
this.selected = selected;
}
// ------------------------------------------------------------------------------------------------------------------
// Custom painting methods
// ------------------------------------------------------------------------------------------------------------------
public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets vInsets = c.getInsets();
int w = c.getWidth() - (vInsets.left + vInsets.right);
int h = c.getHeight() - (vInsets.top + vInsets.bottom);
int x = vInsets.left;
int y = vInsets.top;
int arc = 8;
Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc);
Shape vOldClip = g.getClip();
- g2d.setClip(vButtonShape);
+ if(!Spark.isMac()){
+ g2d.setClip(vButtonShape);
+ }
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, h);
g2d.setClip(vOldClip);
GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight);
g2d.setPaint(vPaint);
// Handle custom actions.
if (placement == JTabbedPane.TOP) {
if (selected) {
g2d.setColor(Color.lightGray);
g2d.drawRoundRect(x, y, w, h, arc, arc);
}
g2d.clipRect(x, y, w + 1, h - arc / 4);
g2d.setColor(borderColorAlpha1);
g2d.setClip(vOldClip);
g2d.setColor(borderColorAlpha2);
g2d.setColor(backgroundColor2);
g2d.fillRect(x, h - 5, w, h);
}
else {
// Make straight line.
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, 4);
}
if (selected) {
}
else if (!hideBorder) {
// Draw border on right side.
g2d.setColor(Color.lightGray);
g2d.drawLine(w - 1, 4, w - 1, h - 4);
}
}
public void setHideBorder(boolean hide) {
hideBorder = hide;
}
private Color getSelectedStartColor() {
Color uiStartColor = (Color)UIManager.get("SparkTabbedPane.startColor");
if (uiStartColor != null) {
return uiStartColor;
}
if (Spark.isCustomBuild()) {
String end = Default.getString(Default.CONTACT_GROUP_END_COLOR);
return getColor(end);
}
else {
return new Color(193, 216, 248);
}
}
private Color getSelectedEndColor() {
Color uiEndColor = (Color)UIManager.get("SparkTabbedPane.endColor");
if (uiEndColor != null) {
return uiEndColor;
}
if (Spark.isCustomBuild()) {
String end = Default.getString(Default.CONTACT_GROUP_END_COLOR);
return getColor(end);
}
else {
return new Color(180, 207, 247);
}
}
private static Color getColor(String commaColorString) {
Color color = null;
try {
color = null;
StringTokenizer tkn = new StringTokenizer(commaColorString, ",");
color = new Color(Integer.parseInt(tkn.nextToken()), Integer.parseInt(tkn.nextToken()), Integer.parseInt(tkn.nextToken()));
}
catch (NumberFormatException e1) {
Log.error(e1);
return Color.white;
}
return color;
}
public void setPlacement(int placement) {
this.placement = placement;
}
}
| true | true | public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets vInsets = c.getInsets();
int w = c.getWidth() - (vInsets.left + vInsets.right);
int h = c.getHeight() - (vInsets.top + vInsets.bottom);
int x = vInsets.left;
int y = vInsets.top;
int arc = 8;
Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc);
Shape vOldClip = g.getClip();
g2d.setClip(vButtonShape);
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, h);
g2d.setClip(vOldClip);
GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight);
g2d.setPaint(vPaint);
// Handle custom actions.
if (placement == JTabbedPane.TOP) {
if (selected) {
g2d.setColor(Color.lightGray);
g2d.drawRoundRect(x, y, w, h, arc, arc);
}
g2d.clipRect(x, y, w + 1, h - arc / 4);
g2d.setColor(borderColorAlpha1);
g2d.setClip(vOldClip);
g2d.setColor(borderColorAlpha2);
g2d.setColor(backgroundColor2);
g2d.fillRect(x, h - 5, w, h);
}
else {
// Make straight line.
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, 4);
}
if (selected) {
}
else if (!hideBorder) {
// Draw border on right side.
g2d.setColor(Color.lightGray);
g2d.drawLine(w - 1, 4, w - 1, h - 4);
}
}
| public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets vInsets = c.getInsets();
int w = c.getWidth() - (vInsets.left + vInsets.right);
int h = c.getHeight() - (vInsets.top + vInsets.bottom);
int x = vInsets.left;
int y = vInsets.top;
int arc = 8;
Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc);
Shape vOldClip = g.getClip();
if(!Spark.isMac()){
g2d.setClip(vButtonShape);
}
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, h);
g2d.setClip(vOldClip);
GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight);
g2d.setPaint(vPaint);
// Handle custom actions.
if (placement == JTabbedPane.TOP) {
if (selected) {
g2d.setColor(Color.lightGray);
g2d.drawRoundRect(x, y, w, h, arc, arc);
}
g2d.clipRect(x, y, w + 1, h - arc / 4);
g2d.setColor(borderColorAlpha1);
g2d.setClip(vOldClip);
g2d.setColor(borderColorAlpha2);
g2d.setColor(backgroundColor2);
g2d.fillRect(x, h - 5, w, h);
}
else {
// Make straight line.
g2d.setColor(backgroundColor2);
g2d.fillRect(x, y, w, 4);
}
if (selected) {
}
else if (!hideBorder) {
// Draw border on right side.
g2d.setColor(Color.lightGray);
g2d.drawLine(w - 1, 4, w - 1, h - 4);
}
}
|
diff --git a/src/main/java/libshapedraw/internal/Controller.java b/src/main/java/libshapedraw/internal/Controller.java
index 2873127..693c62f 100644
--- a/src/main/java/libshapedraw/internal/Controller.java
+++ b/src/main/java/libshapedraw/internal/Controller.java
@@ -1,226 +1,225 @@
package libshapedraw.internal;
import java.util.LinkedHashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import libshapedraw.ApiInfo;
import libshapedraw.LibShapeDraw;
import libshapedraw.MinecraftAccess;
import libshapedraw.animation.trident.TridentConfig;
import libshapedraw.event.LSDEventListener;
import libshapedraw.event.LSDGameTickEvent;
import libshapedraw.event.LSDPreRenderEvent;
import libshapedraw.event.LSDRespawnEvent;
import libshapedraw.internal.Util.FileLogger;
import libshapedraw.internal.Util.NullLogger;
import libshapedraw.primitive.ReadonlyVector3;
import libshapedraw.shape.Shape;
import org.lwjgl.opengl.GL11;
/**
* Internal singleton controller class, lazily instantiated.
* Relies on a bootstrapper (mod_LibShapeDraw) to feed it Minecraft game events.
*/
public class Controller {
private static Controller instance;
private final Logger log;
private final LinkedHashSet<LibShapeDraw> apiInstances;
private int topApiInstanceId;
private MinecraftAccess minecraftAccess;
private boolean initialized;
private long lastDump;
private Controller() {
if (GlobalSettings.isLoggingEnabled()) {
log = new FileLogger(ModDirectory.DIRECTORY, ApiInfo.getName(), GlobalSettings.isLoggingAppend());
} else {
log = new NullLogger();
}
apiInstances = new LinkedHashSet<LibShapeDraw>();
topApiInstanceId = 0;
TridentConfig trident = TridentConfig.getInstance();
trident.addPropertyInterpolator(new ReadonlyColorPropertyInterpolator());
trident.addPropertyInterpolator(new ReadonlyVector3PropertyInterpolator());
trident.addPropertyInterpolator(new ReadonlyLineStylePropertyInterpolator());
log.info(ApiInfo.getName() + " v" + ApiInfo.getVersion() + " by " + ApiInfo.getAuthors());
log.info(ApiInfo.getUrl());
log.info(getClass().getName() + " instantiated");
}
public static Controller getInstance() {
if (instance == null) {
instance = new Controller();
}
return instance;
}
public static Logger getLog() {
return getInstance().log;
}
public static MinecraftAccess getMinecraftAccess() {
return getInstance().minecraftAccess;
}
/**
* @return true if the bootstrapper has been instantiated and is linked up to the controller
*/
public static boolean isInitialized() {
return getInstance().initialized;
}
/**
* Called by the bootstrapper.
*/
public void initialize(MinecraftAccess minecraftAccess) {
if (isInitialized()) {
throw new IllegalStateException("multiple initializations of controller");
}
this.minecraftAccess = minecraftAccess;
initialized = true;
log.info(getClass().getName() + " initialized");
}
/**
* Called by LibShapeDraw's constructor.
*/
public String registerApiInstance(LibShapeDraw apiInstance, String ownerId) {
if (apiInstances.contains(apiInstance)) {
throw new IllegalStateException("already registered");
}
topApiInstanceId++;
String apiInstanceId = apiInstance.getClass().getSimpleName() + "#" + topApiInstanceId + ":" + ownerId;
apiInstances.add(apiInstance);
log.info("registered API instance " + apiInstanceId);
return apiInstanceId;
}
/**
* Called by LibShapeDraw.unregister.
*/
public boolean unregisterApiInstance(LibShapeDraw apiInstance) {
boolean result = apiInstances.remove(apiInstance);
if (result) {
log.info("unregistered API instance " + apiInstance.getInstanceId());
}
return result;
}
/**
* Called by the bootstrapper.
* Dispatch the respawn event.
*/
public void respawn(ReadonlyVector3 playerCoords, boolean isNewServer, boolean isNewDimension) {
log.finer("respawn");
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDRespawnEvent event = new LSDRespawnEvent(apiInstance, playerCoords, isNewServer, isNewDimension);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
listener.onRespawn(event);
}
}
}
}
/**
* Called by the bootstrapper.
* Periodically dump API state to log if configured to do so.
* Dispatch gameTick events.
*/
public void gameTick(ReadonlyVector3 playerCoords) {
log.finer("gameTick");
if (GlobalSettings.getLoggingDebugDumpInterval() > 0) {
long now = System.currentTimeMillis();
if (now > lastDump + GlobalSettings.getLoggingDebugDumpInterval()) {
dump();
lastDump = now;
}
}
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDGameTickEvent event = new LSDGameTickEvent(apiInstance, playerCoords);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onGameTick(event);
}
}
}
}
}
/**
* Called by the bootstrapper.
* Dispatch preRender events.
* Render all registered shapes.
*/
public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) {
log.finer("render");
int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC);
GL11.glPushMatrix();
GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ());
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onPreRender(event);
}
}
}
if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) {
for (Shape shape : apiInstance.getShapes()) {
if (shape != null) {
shape.render(minecraftAccess);
}
}
}
}
GL11.glPopMatrix();
GL11.glDepthMask(true);
GL11.glDepthFunc(origDepthFunc);
- GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
/**
* Log all the things.
*/
public boolean dump() {
if (!log.isLoggable(Level.INFO)) {
return false;
}
final String INDENT = " ";
StringBuilder line = new StringBuilder().append(this).append(":\n");
for (LibShapeDraw apiInstance : apiInstances) {
line.append(INDENT).append(apiInstance).append(":\n");
line.append(INDENT).append(INDENT).append("visible=");
line.append(apiInstance.isVisible()).append('\n');
line.append(INDENT).append(INDENT).append("visibleWhenHidingGui=");
line.append(apiInstance.isVisibleWhenHidingGui()).append('\n');
line.append(INDENT).append(INDENT).append("shapes=");
line.append(apiInstance.getShapes().size()).append(":\n");
for (Shape shape : apiInstance.getShapes()) {
line.append(INDENT).append(INDENT).append(INDENT).append(shape).append('\n');
}
line.append(INDENT).append(INDENT).append("eventListeners=");
line.append(apiInstance.getEventListeners().size()).append(":\n");
for (LSDEventListener listener : apiInstance.getEventListeners()) {
line.append(INDENT).append(INDENT).append(INDENT).append(listener).append('\n');
}
}
log.info(line.toString());
return true;
}
}
| true | true | public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) {
log.finer("render");
int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC);
GL11.glPushMatrix();
GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ());
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onPreRender(event);
}
}
}
if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) {
for (Shape shape : apiInstance.getShapes()) {
if (shape != null) {
shape.render(minecraftAccess);
}
}
}
}
GL11.glPopMatrix();
GL11.glDepthMask(true);
GL11.glDepthFunc(origDepthFunc);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
| public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) {
log.finer("render");
int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC);
GL11.glPushMatrix();
GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ());
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onPreRender(event);
}
}
}
if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) {
for (Shape shape : apiInstance.getShapes()) {
if (shape != null) {
shape.render(minecraftAccess);
}
}
}
}
GL11.glPopMatrix();
GL11.glDepthMask(true);
GL11.glDepthFunc(origDepthFunc);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
|
diff --git a/src/com/delin/speedlogger/Activities/DevPrefsActivity.java b/src/com/delin/speedlogger/Activities/DevPrefsActivity.java
index 68093fa..f743f03 100644
--- a/src/com/delin/speedlogger/Activities/DevPrefsActivity.java
+++ b/src/com/delin/speedlogger/Activities/DevPrefsActivity.java
@@ -1,43 +1,47 @@
package com.delin.speedlogger.Activities;
import java.io.File;
import com.delin.speedlogger.R;
import android.os.Bundle;
import android.os.Environment;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class DevPrefsActivity extends PreferenceActivity {
static final String CREATOR_VALUE = "SpeedLogger";
static final String STORAGE_DIR = Environment.getExternalStorageDirectory().getPath() +"/"+CREATOR_VALUE;
static final String GPS_DIR_NAME = "FileGPS";
static final String GPS_DIR_PATH = STORAGE_DIR + "/" + GPS_DIR_NAME;
ListPreference gpxFiles;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String prefsName = getString(R.string.DevPrefs);
getPreferenceManager().setSharedPreferencesName(prefsName);
addPreferencesFromResource(R.xml.dev_preferences);
gpxFiles = (ListPreference) findPreference(getString(R.string.FileWithGPS));
FindGPX();
}
// adds all filenames from GPS folder into the gpx list
private void FindGPX() {
File dir = new File(GPS_DIR_PATH);
try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;}
- String[] filenames = dir.list();
- if (filenames.length > 0) {
- gpxFiles.setEntries(filenames);
- for(int i=0; i<filenames.length; ++i) {
- filenames[i] = GPS_DIR_NAME + "/" + filenames[i];
+ String[] filenameEntries = dir.list();
+ String[] filenameValues;
+ if (filenameEntries.length > 0) {
+ // list entries
+ gpxFiles.setEntries(filenameEntries);
+ // list values
+ filenameValues = filenameEntries.clone();
+ for(int i=0; i<filenameValues.length; ++i) {
+ filenameValues[i] = GPS_DIR_NAME + "/" + filenameValues[i];
}
- gpxFiles.setEntryValues(filenames);
+ gpxFiles.setEntryValues(filenameValues);
if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0);
}
}
}
| false | true | private void FindGPX() {
File dir = new File(GPS_DIR_PATH);
try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;}
String[] filenames = dir.list();
if (filenames.length > 0) {
gpxFiles.setEntries(filenames);
for(int i=0; i<filenames.length; ++i) {
filenames[i] = GPS_DIR_NAME + "/" + filenames[i];
}
gpxFiles.setEntryValues(filenames);
if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0);
}
}
| private void FindGPX() {
File dir = new File(GPS_DIR_PATH);
try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;}
String[] filenameEntries = dir.list();
String[] filenameValues;
if (filenameEntries.length > 0) {
// list entries
gpxFiles.setEntries(filenameEntries);
// list values
filenameValues = filenameEntries.clone();
for(int i=0; i<filenameValues.length; ++i) {
filenameValues[i] = GPS_DIR_NAME + "/" + filenameValues[i];
}
gpxFiles.setEntryValues(filenameValues);
if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0);
}
}
|
diff --git a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java
index 8c417bb..e5b5b90 100644
--- a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java
+++ b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java
@@ -1,113 +1,112 @@
package fr.iutvalence.java.mp.thelasttyper.client.data;
/**
* This class contains all the informations about a word. The word have to be
* destroyed in the game.
*
* @author culasb
*/
public class Word
{
/**
* Word score value. When the this word is killed by a player, this value is
* added to the player's score this value cannot be changed
*
*/
private final int value;
/**
* Word's level
*
* this value cannot be changed
*/
private final int difficulty;
/**
* Word's content (string) this value cannot be changed
*/
private final String content;
/**
* Instantiation of new word with a given value, a given level, and a given
* content.
*
* @param value
* Default score Value for this word
* @param difficulty
* Word level
* @param content
* the string
*/
public Word(int value, int difficulty, String content)
{
this.value = value;
this.difficulty = difficulty;
this.content = content;
}
/**
* static method to get the difficulty of a given string
* @param s the string which need to be tested
* @return the difficulty
*/
public static int getDifficulty(String s)
{
int i = s.length();
- if (i ==0)
- //TODO throw exception EmptyStringException
+ if (i ==0) return 0;
if (i < 4)
return 1;
else if (i< 5)
return 2;
else if (i< 6)
return 3;
else if (i <8)
return 4;
//else
return 5;
}
/**
* this static method return the value of a string.
* @param s the given which need to be tested
* @return its value.
*/
public static int getValue (String s){
return (Word.getDifficulty(s) * 100);
}
/**
* get the score value of the Word
*
* @return score value
*/
public int getValue()
{
return this.value;
}
/**
* get the level of the Word
*
* @return word's level
*/
public int getDifficulty()
{
return this.difficulty;
}
/**
* get the content of the Word
*
* @return word's content.
*/
public String getContent()
{
return this.content;
}
}
| true | true | public static int getDifficulty(String s)
{
int i = s.length();
if (i ==0)
//TODO throw exception EmptyStringException
if (i < 4)
return 1;
else if (i< 5)
return 2;
else if (i< 6)
return 3;
else if (i <8)
return 4;
//else
return 5;
}
| public static int getDifficulty(String s)
{
int i = s.length();
if (i ==0) return 0;
if (i < 4)
return 1;
else if (i< 5)
return 2;
else if (i< 6)
return 3;
else if (i <8)
return 4;
//else
return 5;
}
|
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java b/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java
index afc67bd..cb2ca50 100644
--- a/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java
+++ b/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java
@@ -1,58 +1,58 @@
package jp.ac.osaka_u.ist.sdl.ectec.ast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
/**
* A class to create ASTs from the given source files
*
* @author k-hotta
*
*/
public class ASTCreator {
public static CompilationUnit createAST(final String sourceCode) {
final ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(sourceCode.toCharArray());
return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
- public static CompilationUnit creatAST(final File file) {
+ public static CompilationUnit createAST(final File file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
final StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
return createAST(builder.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| true | true | public static CompilationUnit creatAST(final File file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
final StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
return createAST(builder.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| public static CompilationUnit createAST(final File file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
final StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
return createAST(builder.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
diff --git a/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java b/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java
index 6ca2b614..c56648a5 100644
--- a/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java
+++ b/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java
@@ -1,258 +1,258 @@
/*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.server.pluggableTask;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.sapienter.jbilling.server.item.db.ItemTypeDTO;
import com.sapienter.jbilling.server.order.OrderLineComparator;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.server.item.ItemDecimalsException;
import com.sapienter.jbilling.server.item.db.ItemDAS;
import com.sapienter.jbilling.server.item.db.ItemDTO;
import com.sapienter.jbilling.server.order.db.OrderDTO;
import com.sapienter.jbilling.server.order.db.OrderLineDTO;
import com.sapienter.jbilling.server.util.Constants;
/**
* Basic tasks that takes the quantity and multiplies it by the price to
* get the lines total. It also updates the order total with the addition
* of all line totals
*
*/
public class BasicLineTotalTask extends PluggableTask implements OrderProcessingTask {
private static final Logger LOG = Logger.getLogger(BasicLineTotalTask.class);
private static final BigDecimal ONE_HUNDRED = new BigDecimal("100.00");
public void doProcessing(OrderDTO order) throws TaskException {
validateLinesQuantity(order.getLines());
clearLineTotals(order.getLines());
ItemDAS itemDas = new ItemDAS();
/*
Calculate non-percentage items, calculating price as $/unit
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO item = itemDas.find(line.getItemId());
if (item != null && item.getPercentage() == null) {
line.setAmount(line.getQuantity().multiply(line.getPrice()));
LOG.debug("normal line total: "
+ line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount());
}
}
/*
Calculate non-tax percentage items (fees).
Percentages are not compounded and charged only on normal item lines
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO percentageItem = itemDas.find(line.getItemId());
if (percentageItem != null
&& percentageItem.getPercentage() != null
&& !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges * percentage
BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes());
- line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_ROUND).multiply(total));
+ line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND).multiply(total));
LOG.debug("percentage line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
/*
Calculate tax percentage items.
Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees).
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO taxItem = itemDas.find(line.getItemId());
if (taxItem != null
&& taxItem.getPercentage() != null
&& line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges + fees * percentage
BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes());
- line.setAmount(line.getPrice().divide(ONE_HUNDRED, BigDecimal.ROUND_HALF_EVEN).multiply(total));
+ line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, BigDecimal.ROUND_HALF_EVEN).multiply(total));
LOG.debug("tax line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
// order total
order.setTotal(getTotal(order.getLines()));
LOG.debug("Order total = " + order.getTotal());
}
/**
* Returns the sum total amount of all lines with items that do NOT belong to the given excluded type list.
*
* This total only includes normal item lines and not tax or penalty lines.
*
* @param lines order lines
* @param excludedTypes excluded item types
* @return total amount
*/
public BigDecimal getTotalForPercentage(List<OrderLineDTO> lines, Set<ItemTypeDTO> excludedTypes) {
BigDecimal total = BigDecimal.ZERO;
for (OrderLineDTO line : lines) {
if (line.getDeleted() == 1) continue;
// add line total for non-percentage & non-tax lines
if (line.getItem().getPercentage() == null && line.getTypeId().equals(Constants.ORDER_LINE_TYPE_ITEM)) {
// add if type is not in the excluded list
if (!isItemExcluded(line.getItem(), excludedTypes)) {
total = total.add(line.getAmount());
} else {
LOG.debug("item " + line.getItem().getId() + " excluded from percentage.");
}
}
}
LOG.debug("total amount applicable for percentage: " + total);
return total;
}
/**
* Returns the sum total amount of all lines with items that do NOT belong to the given excluded type list.
*
* This total includes all non tax lines (i.e., normal items, percentage fees and penalty lines).
*
* @param lines order lines
* @param excludedTypes excluded item types
* @return total amount
*/
public BigDecimal getTotalForTax(List<OrderLineDTO> lines, Set<ItemTypeDTO> excludedTypes) {
BigDecimal total = BigDecimal.ZERO;
for (OrderLineDTO line : lines) {
if (line.getDeleted() == 1) continue;
// add line total for all non-tax items
if (!line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// add if type is not in the excluded list
if (!isItemExcluded(line.getItem(), excludedTypes)) {
total = total.add(line.getAmount());
} else {
LOG.debug("item " + line.getItem().getId() + " excluded from tax.");
}
}
}
LOG.debug("total amount applicable for tax: " + total);
return total;
}
/**
* Returns true if the item is in the excluded item type list.
*
* @param item item to check
* @param excludedTypes list of excluded item types
* @return true if item is excluded, false if not
*/
private boolean isItemExcluded(ItemDTO item, Set<ItemTypeDTO> excludedTypes) {
for (ItemTypeDTO excludedType : excludedTypes) {
for (ItemTypeDTO itemType : item.getItemTypes()) {
if (itemType.getId() == excludedType.getId()) {
return true;
}
}
}
return false;
}
/**
* Returns the total of all given order lines.
*
* @param lines order lines
* @return total amount
*/
public BigDecimal getTotal(List<OrderLineDTO> lines) {
BigDecimal total = BigDecimal.ZERO;
for (OrderLineDTO line : lines) {
if (line.getDeleted() == 1) continue;
// add total
total = total.add(line.getAmount());
}
return total;
}
/**
* Sets all order line amounts to null.
*
* @param lines order lines to clear
*/
public void clearLineTotals(List<OrderLineDTO> lines) {
for (OrderLineDTO line : lines) {
if (line.getDeleted() == 1) continue;
// clear amount
line.setAmount(null);
}
}
/**
* Validates that only order line items with {@link ItemDTO#hasDecimals} set to true has
* a decimal quantity.
*
* @param lines order lines to validate
* @throws TaskException thrown if an order line has decimals without the item hasDecimals flag
*/
public void validateLinesQuantity(List<OrderLineDTO> lines) throws TaskException {
for (OrderLineDTO line : lines) {
if (line.getDeleted() == 1) continue;
// validate line quantity
if (line.getItem() != null
&& line.getQuantity().remainder(Constants.BIGDECIMAL_ONE).compareTo(BigDecimal.ZERO) != 0.0
&& line.getItem().getHasDecimals() == 0) {
throw new TaskException(new ItemDecimalsException("Item does not allow Decimals"));
}
}
}
}
| false | true | public void doProcessing(OrderDTO order) throws TaskException {
validateLinesQuantity(order.getLines());
clearLineTotals(order.getLines());
ItemDAS itemDas = new ItemDAS();
/*
Calculate non-percentage items, calculating price as $/unit
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO item = itemDas.find(line.getItemId());
if (item != null && item.getPercentage() == null) {
line.setAmount(line.getQuantity().multiply(line.getPrice()));
LOG.debug("normal line total: "
+ line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount());
}
}
/*
Calculate non-tax percentage items (fees).
Percentages are not compounded and charged only on normal item lines
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO percentageItem = itemDas.find(line.getItemId());
if (percentageItem != null
&& percentageItem.getPercentage() != null
&& !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges * percentage
BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes());
line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_ROUND).multiply(total));
LOG.debug("percentage line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
/*
Calculate tax percentage items.
Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees).
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO taxItem = itemDas.find(line.getItemId());
if (taxItem != null
&& taxItem.getPercentage() != null
&& line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges + fees * percentage
BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes());
line.setAmount(line.getPrice().divide(ONE_HUNDRED, BigDecimal.ROUND_HALF_EVEN).multiply(total));
LOG.debug("tax line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
// order total
order.setTotal(getTotal(order.getLines()));
LOG.debug("Order total = " + order.getTotal());
}
| public void doProcessing(OrderDTO order) throws TaskException {
validateLinesQuantity(order.getLines());
clearLineTotals(order.getLines());
ItemDAS itemDas = new ItemDAS();
/*
Calculate non-percentage items, calculating price as $/unit
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO item = itemDas.find(line.getItemId());
if (item != null && item.getPercentage() == null) {
line.setAmount(line.getQuantity().multiply(line.getPrice()));
LOG.debug("normal line total: "
+ line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount());
}
}
/*
Calculate non-tax percentage items (fees).
Percentages are not compounded and charged only on normal item lines
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO percentageItem = itemDas.find(line.getItemId());
if (percentageItem != null
&& percentageItem.getPercentage() != null
&& !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges * percentage
BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes());
line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND).multiply(total));
LOG.debug("percentage line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
/*
Calculate tax percentage items.
Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees).
*/
for (OrderLineDTO line : order.getLines()) {
if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue;
// calculate line total
ItemDTO taxItem = itemDas.find(line.getItemId());
if (taxItem != null
&& taxItem.getPercentage() != null
&& line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) {
// sum of applicable item charges + fees * percentage
BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes());
line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, BigDecimal.ROUND_HALF_EVEN).multiply(total));
LOG.debug("tax line total: %" + line.getPrice() + "; "
+ "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount());
}
}
// order total
order.setTotal(getTotal(order.getLines()));
LOG.debug("Order total = " + order.getTotal());
}
|
diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
index 6c43e78f9..f55ae4e43 100644
--- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
+++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
@@ -1,318 +1,318 @@
/*
* Copyright 2002-2012 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.orm.hibernate3.support;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.async.AbstractDelegatingCallable;
import org.springframework.web.context.request.async.AsyncExecutionChain;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Servlet 2.3 Filter that binds a Hibernate Session to the thread for the entire
* processing of the request. Intended for the "Open Session in View" pattern,
* i.e. to allow for lazy loading in web views despite the original transactions
* already being completed.
*
* <p>This filter makes Hibernate Sessions available via the current thread, which
* will be autodetected by transaction managers. It is suitable for service layer
* transactions via {@link org.springframework.orm.hibernate3.HibernateTransactionManager}
* or {@link org.springframework.transaction.jta.JtaTransactionManager} as well
* as for non-transactional execution (if configured appropriately).
*
* <p><b>NOTE</b>: This filter will by default <i>not</i> flush the Hibernate Session,
* with the flush mode set to <code>FlushMode.NEVER</code>. It assumes to be used
* in combination with service layer transactions that care for the flushing: The
* active transaction manager will temporarily change the flush mode to
* <code>FlushMode.AUTO</code> during a read-write transaction, with the flush
* mode reset to <code>FlushMode.NEVER</code> at the end of each transaction.
* If you intend to use this filter without transactions, consider changing
* the default flush mode (through the "flushMode" property).
*
* <p><b>WARNING:</b> Applying this filter to existing logic can cause issues that
* have not appeared before, through the use of a single Hibernate Session for the
* processing of an entire request. In particular, the reassociation of persistent
* objects with a Hibernate Session has to occur at the very beginning of request
* processing, to avoid clashes with already loaded instances of the same objects.
*
* <p>Alternatively, turn this filter into deferred close mode, by specifying
* "singleSession"="false": It will not use a single session per request then,
* but rather let each data access operation or transaction use its own session
* (like without Open Session in View). Each of those sessions will be registered
* for deferred close, though, actually processed at request completion.
*
* <p>A single session per request allows for most efficient first-level caching,
* but can cause side effects, for example on <code>saveOrUpdate</code> or when
* continuing after a rolled-back transaction. The deferred close strategy is as safe
* as no Open Session in View in that respect, while still allowing for lazy loading
* in views (but not providing a first-level cache for the entire request).
*
* <p>Looks up the SessionFactory in Spring's root web application context.
* Supports a "sessionFactoryBeanName" filter init-param in <code>web.xml</code>;
* the default bean name is "sessionFactory". Looks up the SessionFactory on each
* request, to avoid initialization order issues (when using ContextLoaderServlet,
* the root application context will get initialized <i>after</i> this filter).
*
* @author Juergen Hoeller
* @since 1.2
* @see #setSingleSession
* @see #setFlushMode
* @see #lookupSessionFactory
* @see OpenSessionInViewInterceptor
* @see org.springframework.orm.hibernate3.HibernateInterceptor
* @see org.springframework.orm.hibernate3.HibernateTransactionManager
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
* @see org.springframework.transaction.support.TransactionSynchronizationManager
*/
public class OpenSessionInViewFilter extends OncePerRequestFilter {
public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";
private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME;
private boolean singleSession = true;
private FlushMode flushMode = FlushMode.MANUAL;
/**
* Set the bean name of the SessionFactory to fetch from Spring's
* root application context. Default is "sessionFactory".
* @see #DEFAULT_SESSION_FACTORY_BEAN_NAME
*/
public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
this.sessionFactoryBeanName = sessionFactoryBeanName;
}
/**
* Return the bean name of the SessionFactory to fetch from Spring's
* root application context.
*/
protected String getSessionFactoryBeanName() {
return this.sessionFactoryBeanName;
}
/**
* Set whether to use a single session for each request. Default is "true".
* <p>If set to "false", each data access operation or transaction will use
* its own session (like without Open Session in View). Each of those
* sessions will be registered for deferred close, though, actually
* processed at request completion.
* @see SessionFactoryUtils#initDeferredClose
* @see SessionFactoryUtils#processDeferredClose
*/
public void setSingleSession(boolean singleSession) {
this.singleSession = singleSession;
}
/**
* Return whether to use a single session for each request.
*/
protected boolean isSingleSession() {
return this.singleSession;
}
/**
* Specify the Hibernate FlushMode to apply to this filter's
* {@link org.hibernate.Session}. Only applied in single session mode.
* <p>Can be populated with the corresponding constant name in XML bean
* definitions: e.g. "AUTO".
* <p>The default is "MANUAL". Specify "AUTO" if you intend to use
* this filter without service layer transactions.
* @see org.hibernate.Session#setFlushMode
* @see org.hibernate.FlushMode#MANUAL
* @see org.hibernate.FlushMode#AUTO
*/
public void setFlushMode(FlushMode flushMode) {
this.flushMode = flushMode;
}
/**
* Return the Hibernate FlushMode that this filter applies to its
* {@link org.hibernate.Session} (in single session mode).
*/
protected FlushMode getFlushMode() {
return this.flushMode;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request);
SessionFactory sessionFactory = lookupSessionFactory(request);
boolean participate = false;
if (isSingleSession()) {
// single session mode
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
// Do not modify the Session: just set the participate flag.
participate = true;
}
else {
logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
Session session = getSession(sessionFactory);
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
chain.push(getAsyncCallable(request, sessionFactory, sessionHolder));
}
}
else {
// deferred close mode
if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
// Do not modify deferred close: just set the participate flag.
participate = true;
}
else {
SessionFactoryUtils.initDeferredClose(sessionFactory);
}
}
try {
filterChain.doFilter(request, response);
}
finally {
if (!participate) {
if (isSingleSession()) {
// single session mode
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
if (!chain.pop()) {
return;
}
logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
closeSession(sessionHolder.getSession(), sessionFactory);
}
else {
- if (!chain.pop()) {
+ if (chain.isAsyncStarted()) {
throw new IllegalStateException("Deferred close is not supported with async requests.");
}
// deferred close mode
SessionFactoryUtils.processDeferredClose(sessionFactory);
}
}
}
}
/**
* Look up the SessionFactory that this filter should use,
* taking the current HTTP request as argument.
* <p>The default implementation delegates to the {@link #lookupSessionFactory()}
* variant without arguments.
* @param request the current request
* @return the SessionFactory to use
*/
protected SessionFactory lookupSessionFactory(HttpServletRequest request) {
return lookupSessionFactory();
}
/**
* Look up the SessionFactory that this filter should use.
* <p>The default implementation looks for a bean with the specified name
* in Spring's root application context.
* @return the SessionFactory to use
* @see #getSessionFactoryBeanName
*/
protected SessionFactory lookupSessionFactory() {
if (logger.isDebugEnabled()) {
logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
}
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}
/**
* Get a Session for the SessionFactory that this filter uses.
* Note that this just applies in single session mode!
* <p>The default implementation delegates to the
* <code>SessionFactoryUtils.getSession</code> method and
* sets the <code>Session</code>'s flush mode to "MANUAL".
* <p>Can be overridden in subclasses for creating a Session with a
* custom entity interceptor or JDBC exception translator.
* @param sessionFactory the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
* @see org.hibernate.FlushMode#MANUAL
*/
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
FlushMode flushMode = getFlushMode();
if (flushMode != null) {
session.setFlushMode(flushMode);
}
return session;
}
/**
* Close the given Session.
* Note that this just applies in single session mode!
* <p>Can be overridden in subclasses, e.g. for flushing the Session before
* closing it. See class-level javadoc for a discussion of flush handling.
* Note that you should also override getSession accordingly, to set
* the flush mode to something else than NEVER.
* @param session the Session used for filtering
* @param sessionFactory the SessionFactory that this filter uses
*/
protected void closeSession(Session session, SessionFactory sessionFactory) {
SessionFactoryUtils.closeSession(session);
}
/**
* Create a Callable to extend the use of the open Hibernate Session to the
* async thread completing the request.
*/
private AbstractDelegatingCallable getAsyncCallable(final HttpServletRequest request,
final SessionFactory sessionFactory, final SessionHolder sessionHolder) {
return new AbstractDelegatingCallable() {
public Object call() throws Exception {
TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
try {
getNext().call();
}
finally {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}
return null;
}
};
}
}
| true | true | protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request);
SessionFactory sessionFactory = lookupSessionFactory(request);
boolean participate = false;
if (isSingleSession()) {
// single session mode
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
// Do not modify the Session: just set the participate flag.
participate = true;
}
else {
logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
Session session = getSession(sessionFactory);
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
chain.push(getAsyncCallable(request, sessionFactory, sessionHolder));
}
}
else {
// deferred close mode
if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
// Do not modify deferred close: just set the participate flag.
participate = true;
}
else {
SessionFactoryUtils.initDeferredClose(sessionFactory);
}
}
try {
filterChain.doFilter(request, response);
}
finally {
if (!participate) {
if (isSingleSession()) {
// single session mode
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
if (!chain.pop()) {
return;
}
logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
closeSession(sessionHolder.getSession(), sessionFactory);
}
else {
if (!chain.pop()) {
throw new IllegalStateException("Deferred close is not supported with async requests.");
}
// deferred close mode
SessionFactoryUtils.processDeferredClose(sessionFactory);
}
}
}
}
| protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request);
SessionFactory sessionFactory = lookupSessionFactory(request);
boolean participate = false;
if (isSingleSession()) {
// single session mode
if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
// Do not modify the Session: just set the participate flag.
participate = true;
}
else {
logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
Session session = getSession(sessionFactory);
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
chain.push(getAsyncCallable(request, sessionFactory, sessionHolder));
}
}
else {
// deferred close mode
if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
// Do not modify deferred close: just set the participate flag.
participate = true;
}
else {
SessionFactoryUtils.initDeferredClose(sessionFactory);
}
}
try {
filterChain.doFilter(request, response);
}
finally {
if (!participate) {
if (isSingleSession()) {
// single session mode
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
if (!chain.pop()) {
return;
}
logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
closeSession(sessionHolder.getSession(), sessionFactory);
}
else {
if (chain.isAsyncStarted()) {
throw new IllegalStateException("Deferred close is not supported with async requests.");
}
// deferred close mode
SessionFactoryUtils.processDeferredClose(sessionFactory);
}
}
}
}
|
diff --git a/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java b/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java
index abdfbb0ec..1969aa4c7 100644
--- a/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java
+++ b/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java
@@ -1,163 +1,163 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.module.mrtdsodsigner;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ejbca.util.CertTools;
import org.jmrtd.SODFile;
import org.signserver.common.ArchiveData;
import org.signserver.common.CryptoTokenOfflineException;
import org.signserver.common.ISignRequest;
import org.signserver.common.IllegalRequestException;
import org.signserver.common.ProcessRequest;
import org.signserver.common.ProcessResponse;
import org.signserver.common.RequestContext;
import org.signserver.common.SODSignRequest;
import org.signserver.common.SODSignResponse;
import org.signserver.common.SignServerException;
import org.signserver.server.cryptotokens.ICryptoToken;
import org.signserver.server.signers.BaseSigner;
/**
* A Signer signing creating a signed SOD file to be stored in ePassports.
*
* Properties:
* <ul>
* <li>DIGESTALGORITHM = Message digest algorithm applied to the datagroups. (Optional)</li>
* <li>SIGNATUREALGORITHM = Signature algorithm for signing the SO(d), should match
* the digest algorithm. (Optional)</li>
* </ul>
*
* @author Markus Kilas
* @version $Id$
*/
public class MRTDSODSigner extends BaseSigner {
private static final Logger log = Logger.getLogger(MRTDSODSigner.class);
/** The digest algorithm, for example SHA1, SHA256. Defaults to SHA256. */
private static final String PROPERTY_DIGESTALGORITHM = "DIGESTALGORITHM";
/** Default value for the digestAlgorithm property */
private static final String DEFAULT_DIGESTALGORITHM = "SHA256";
/** The signature algorithm, for example SHA1withRSA, SHA256withRSA, SHA256withECDSA. Defaults to SHA256withRSA. */
private static final String PROPERTY_SIGNATUREALGORITHM = "SIGNATUREALGORITHM";
/** Default value for the signature algorithm property */
private static final String DEFAULT_SIGNATUREALGORITHM = "SHA256withRSA";
/** Determines if the the data group values should be hashed by the signer. If false we assume they are already hashed. */
private static final String PROPERTY_DODATAGROUPHASHING = "DODATAGROUPHASHING";
/** Default value if the data group values should be hashed by the signer. */
private static final String DEFAULT_DODATAGROUPHASHING = "false";
public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {
if (log.isTraceEnabled()) {
log.trace(">processData");
}
ProcessResponse ret = null;
ISignRequest sReq = (ISignRequest) signRequest;
// Check that the request contains a valid SODSignRequest object.
if (!(signRequest instanceof SODSignRequest)) {
throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest.");
}
SODSignRequest sodRequest = (SODSignRequest) signRequest;
// Construct SOD
SODFile sod;
X509Certificate cert = (X509Certificate) getSigningCertificate();
ICryptoToken token = getCryptoToken();
PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN);
String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN);
if (log.isDebugEnabled()) {
log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert));
}
try {
// Create the SODFile using the data group hashes that was sent to us in the request.
String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM);
String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM);
if (log.isDebugEnabled()) {
log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm);
}
String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING);
Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes();
Map<Integer, byte[]> dghashes = dgvalues;
if (StringUtils.equalsIgnoreCase(doHashing, "true")) {
if (log.isDebugEnabled()) {
log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm);
}
// If true here the "data group hashes" are not really hashes but values that we must hash.
// The input is already decoded (if needed) and nice, so we just need to hash it
dghashes = new HashMap<Integer, byte[]>(16);
for (Integer dgId : dgvalues.keySet()) {
byte[] value = dgvalues.get(dgId);
if (log.isDebugEnabled()) {
log.debug("Hashing data group "+dgId+", value is of length: "+value.length);
}
if ( (value != null) && (value.length > 0) ) {
- MessageDigest digest = MessageDigest.getInstance("SHA1");
+ MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
byte[] result = digest.digest(value);
if (log.isDebugEnabled()) {
log.debug("Resulting hash is of length: "+result.length);
}
dghashes.put(dgId, result);
}
}
}
sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider);
} catch (NoSuchAlgorithmException ex) {
throw new SignServerException("Problem constructing SOD", ex);
} catch (CertificateException ex) {
throw new SignServerException("Problem constructing SOD", ex);
}
// Verify the Signature before returning
try {
boolean verify = sod.checkDocSignature(cert);
if (!verify) {
log.error("Failed to verify the SOD we signed ourselves.");
log.error("Cert: "+cert);
log.error("SOD: "+sod);
throw new SignServerException("Failed to verify the SOD we signed ourselves.");
} else {
log.debug("SOD verified correctly, returning SOD.");
// Return response
byte[] signedbytes = sod.getEncoded();
String fp = CertTools.getFingerprintAsString(signedbytes);
ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes));
}
} catch (GeneralSecurityException e) {
log.error("Error verifying the SOD we signed ourselves. ", e);
}
if (log.isTraceEnabled()) {
log.trace("<processData");
}
return ret;
}
}
| true | true | public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {
if (log.isTraceEnabled()) {
log.trace(">processData");
}
ProcessResponse ret = null;
ISignRequest sReq = (ISignRequest) signRequest;
// Check that the request contains a valid SODSignRequest object.
if (!(signRequest instanceof SODSignRequest)) {
throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest.");
}
SODSignRequest sodRequest = (SODSignRequest) signRequest;
// Construct SOD
SODFile sod;
X509Certificate cert = (X509Certificate) getSigningCertificate();
ICryptoToken token = getCryptoToken();
PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN);
String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN);
if (log.isDebugEnabled()) {
log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert));
}
try {
// Create the SODFile using the data group hashes that was sent to us in the request.
String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM);
String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM);
if (log.isDebugEnabled()) {
log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm);
}
String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING);
Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes();
Map<Integer, byte[]> dghashes = dgvalues;
if (StringUtils.equalsIgnoreCase(doHashing, "true")) {
if (log.isDebugEnabled()) {
log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm);
}
// If true here the "data group hashes" are not really hashes but values that we must hash.
// The input is already decoded (if needed) and nice, so we just need to hash it
dghashes = new HashMap<Integer, byte[]>(16);
for (Integer dgId : dgvalues.keySet()) {
byte[] value = dgvalues.get(dgId);
if (log.isDebugEnabled()) {
log.debug("Hashing data group "+dgId+", value is of length: "+value.length);
}
if ( (value != null) && (value.length > 0) ) {
MessageDigest digest = MessageDigest.getInstance("SHA1");
byte[] result = digest.digest(value);
if (log.isDebugEnabled()) {
log.debug("Resulting hash is of length: "+result.length);
}
dghashes.put(dgId, result);
}
}
}
sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider);
} catch (NoSuchAlgorithmException ex) {
throw new SignServerException("Problem constructing SOD", ex);
} catch (CertificateException ex) {
throw new SignServerException("Problem constructing SOD", ex);
}
// Verify the Signature before returning
try {
boolean verify = sod.checkDocSignature(cert);
if (!verify) {
log.error("Failed to verify the SOD we signed ourselves.");
log.error("Cert: "+cert);
log.error("SOD: "+sod);
throw new SignServerException("Failed to verify the SOD we signed ourselves.");
} else {
log.debug("SOD verified correctly, returning SOD.");
// Return response
byte[] signedbytes = sod.getEncoded();
String fp = CertTools.getFingerprintAsString(signedbytes);
ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes));
}
} catch (GeneralSecurityException e) {
log.error("Error verifying the SOD we signed ourselves. ", e);
}
if (log.isTraceEnabled()) {
log.trace("<processData");
}
return ret;
}
| public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {
if (log.isTraceEnabled()) {
log.trace(">processData");
}
ProcessResponse ret = null;
ISignRequest sReq = (ISignRequest) signRequest;
// Check that the request contains a valid SODSignRequest object.
if (!(signRequest instanceof SODSignRequest)) {
throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest.");
}
SODSignRequest sodRequest = (SODSignRequest) signRequest;
// Construct SOD
SODFile sod;
X509Certificate cert = (X509Certificate) getSigningCertificate();
ICryptoToken token = getCryptoToken();
PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN);
String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN);
if (log.isDebugEnabled()) {
log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert));
}
try {
// Create the SODFile using the data group hashes that was sent to us in the request.
String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM);
String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM);
if (log.isDebugEnabled()) {
log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm);
}
String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING);
Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes();
Map<Integer, byte[]> dghashes = dgvalues;
if (StringUtils.equalsIgnoreCase(doHashing, "true")) {
if (log.isDebugEnabled()) {
log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm);
}
// If true here the "data group hashes" are not really hashes but values that we must hash.
// The input is already decoded (if needed) and nice, so we just need to hash it
dghashes = new HashMap<Integer, byte[]>(16);
for (Integer dgId : dgvalues.keySet()) {
byte[] value = dgvalues.get(dgId);
if (log.isDebugEnabled()) {
log.debug("Hashing data group "+dgId+", value is of length: "+value.length);
}
if ( (value != null) && (value.length > 0) ) {
MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
byte[] result = digest.digest(value);
if (log.isDebugEnabled()) {
log.debug("Resulting hash is of length: "+result.length);
}
dghashes.put(dgId, result);
}
}
}
sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider);
} catch (NoSuchAlgorithmException ex) {
throw new SignServerException("Problem constructing SOD", ex);
} catch (CertificateException ex) {
throw new SignServerException("Problem constructing SOD", ex);
}
// Verify the Signature before returning
try {
boolean verify = sod.checkDocSignature(cert);
if (!verify) {
log.error("Failed to verify the SOD we signed ourselves.");
log.error("Cert: "+cert);
log.error("SOD: "+sod);
throw new SignServerException("Failed to verify the SOD we signed ourselves.");
} else {
log.debug("SOD verified correctly, returning SOD.");
// Return response
byte[] signedbytes = sod.getEncoded();
String fp = CertTools.getFingerprintAsString(signedbytes);
ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes));
}
} catch (GeneralSecurityException e) {
log.error("Error verifying the SOD we signed ourselves. ", e);
}
if (log.isTraceEnabled()) {
log.trace("<processData");
}
return ret;
}
|
diff --git a/q-web/src/main/java/q/web/login/AddLogin.java b/q-web/src/main/java/q/web/login/AddLogin.java
index d503ec5f..68ba905e 100644
--- a/q-web/src/main/java/q/web/login/AddLogin.java
+++ b/q-web/src/main/java/q/web/login/AddLogin.java
@@ -1,64 +1,64 @@
/**
*
*/
package q.web.login;
import q.dao.PeopleDao;
import q.domain.People;
import q.web.DefaultResourceContext;
import q.web.LoginCookie;
import q.web.Resource;
import q.web.ResourceContext;
import q.web.exception.PeopleLoginPasswordException;
import q.web.exception.PeopleNotExistException;
/**
* @author seanlinwang
* @email xalinx at gmail dot com
* @date Feb 20, 2011
*
*/
public class AddLogin extends Resource {
private PeopleDao peopleDao;
public void setPeopleDao(PeopleDao peopleDao) {
this.peopleDao = peopleDao;
}
/*
* (non-Javadoc)
*
* @see q.web.Resource#execute(q.web.ResourceContext)
*/
@Override
public void execute(ResourceContext context) throws Exception {
String email = context.getString("email");
String password = context.getString("password");
People people = this.peopleDao.getPeopleByEmail(email);
if (null == people) {
throw new PeopleNotExistException("email:邮箱不存在");
}
if (!people.getPassword().equals(password)) {
throw new PeopleLoginPasswordException("password:密码错误");
}
context.setModel("people", people);
((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie
if (!context.isApiRequest()) {
if (context.getString("from") == null) {
- context.redirectServletPath("");
+ context.redirectServletPath("/");
}
}
}
/*
* (non-Javadoc)
*
* @see q.web.Resource#validate(q.web.ResourceContext)
*/
@Override
public void validate(ResourceContext context) throws Exception {
}
}
| true | true | public void execute(ResourceContext context) throws Exception {
String email = context.getString("email");
String password = context.getString("password");
People people = this.peopleDao.getPeopleByEmail(email);
if (null == people) {
throw new PeopleNotExistException("email:邮箱不存在");
}
if (!people.getPassword().equals(password)) {
throw new PeopleLoginPasswordException("password:密码错误");
}
context.setModel("people", people);
((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie
if (!context.isApiRequest()) {
if (context.getString("from") == null) {
context.redirectServletPath("");
}
}
}
| public void execute(ResourceContext context) throws Exception {
String email = context.getString("email");
String password = context.getString("password");
People people = this.peopleDao.getPeopleByEmail(email);
if (null == people) {
throw new PeopleNotExistException("email:邮箱不存在");
}
if (!people.getPassword().equals(password)) {
throw new PeopleLoginPasswordException("password:密码错误");
}
context.setModel("people", people);
((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie
if (!context.isApiRequest()) {
if (context.getString("from") == null) {
context.redirectServletPath("/");
}
}
}
|
diff --git a/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java b/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java
index 206f803f2..6968a59e7 100644
--- a/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java
+++ b/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java
@@ -1,380 +1,380 @@
package com.idega.presentation.remotescripting;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.PresentationObjectContainer;
import com.idega.presentation.Script;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.IFrame;
import com.idega.presentation.ui.InterfaceObject;
import com.idega.presentation.ui.TextInput;
import com.idega.repository.data.RefactorClassRegistry;
/**
* A class for handling remote scripting between two objects.
* @author gimmi
*/
public class RemoteScriptHandler extends PresentationObjectContainer { //implements RemoteScriptable {
private static final String PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS = "prc";
private static final String PARAMETER_SOURCE_NAME = "psn";
public static final String PARAMETER_SOURCE_PARAMETER_NAME = "prmp";
private InterfaceObject source;
private PresentationObject target;
private Map parameters = new HashMap();
private Map toClear = new HashMap();
private String iframeName;
private RemoteScriptCollection remoteScriptCollection;
private boolean sourceIsTrigger = true;
/**
* Default construction should never be used unless
* class is receiving a remote call
*/
public RemoteScriptHandler() {
// Should only be used for remote calls
}
/**
* @param source The source object, that triggers the event
* @param target The target object, the one affected by the event
*/
public RemoteScriptHandler(InterfaceObject source, PresentationObject target) {
this.source = source;
this.target = target;
iframeName = source.getName()+"_"+target.getName();
}
public void main(IWContext iwc) throws Exception{
if (isRemoteCall(iwc)) {
handleRemoteCall(iwc);
} else {
// Adding object if they are not added already
if (source.getParent() == null) {
add(source);
}
if (target.getParent() == null) {
add(target);
}
// source MUST BE added to something before these methods are called
if (sourceIsTrigger) {
if (source instanceof TextInput) {
source.setOnKeyUp(getSubmitEvent(iwc));
} else {
source.setOnChange(getSubmitEvent(iwc));
}
}
addRemoteScriptingScripts(iwc);
}
}
private void addRemoteScriptingScripts(IWContext iwc) {
if (target instanceof DropdownMenu) {
addScriptForDropdown();
} else if (target instanceof Layer) {
addScriptForLayer();
} else {
throw new IllegalArgumentException("Unsupported target instance "+target.getClass().getName());
}
addCallToServer(iwc);
addBuildQueryScript();
addIFrame();
}
private void addCallToServer(IWContext iwc) {
StringBuffer buff = new StringBuffer();
buff.append("var IFrameObj; // our IFrame object").append("\n")
.append("function callToServer_"+iframeName+"(theFormName) {").append("\n")
.append(" if (!document.createElement) {return true};").append("\n")
.append(" var IFrameDoc;").append("\n")
.append(" if (!IFrameObj && document.createElement) {").append("\n")
.append(" // create the IFrame and assign a reference to the").append("\n")
.append(" // object to our global variable IFrameObj.").append("\n")
.append(" // this will only happen the first time") .append("\n")
.append(" // callToServer() is called").append("\n")
.append(" try {").append("\n")
.append(" var tempIFrame=document.createElement('iframe');").append("\n")
.append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n")
.append(" tempIFrame.style.border='0px';").append("\n")
.append(" tempIFrame.style.width='0px';").append("\n")
.append(" tempIFrame.style.height='0px';").append("\n")
.append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n")
.append(" if (document.frames) {").append("\n")
.append(" // this is for IE5 Mac, because it will only").append("\n")
.append(" // allow access to the document object").append("\n")
.append(" // of the IFrame if we access it through").append("\n")
.append(" // the document.frames array").append("\n")
.append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n")
.append(" }").append("\n")
.append(" } catch(exception) {").append("\n")
.append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n")
.append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n")
.append(" // it up by creating our own objects.").append("\n")
.append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n")
.append(" iframeHTML+='border:0px;';").append("\n")
.append(" iframeHTML+='width:0px;';").append("\n")
.append(" iframeHTML+='height:0px;';").append("\n")
.append(" iframeHTML+='\"><\\/iframe>';").append("\n")
.append(" document.body.innerHTML+=iframeHTML;").append("\n")
.append(" IFrameObj = new Object();").append("\n")
.append(" IFrameObj.document = new Object();").append("\n")
.append(" IFrameObj.document.location = new Object();").append("\n")
.append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n")
.append(" IFrameObj.document.location.replace = function(location) {").append("\n")
.append(" this.iframe.src = location;").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n")
.append(" // we have to give NS6 a fraction of a second").append("\n")
.append(" // to recognize the new IFrame").append("\n")
.append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n")
.append(" return false;").append("\n")
.append(" }").append("\n")
.append(" if (IFrameObj.contentDocument) {").append("\n")
.append(" // For NS6").append("\n")
.append(" IFrameDoc = IFrameObj.contentDocument;").append("\n")
.append(" } else if (IFrameObj.contentWindow) {").append("\n")
.append(" // For IE5.5 and IE6").append("\n")
.append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n")
.append(" } else if (IFrameObj.document) {").append("\n")
.append(" // For IE5").append("\n")
.append(" IFrameDoc = IFrameObj.document;").append("\n")
.append(" } else {").append("\n")
.append(" return true;").append("\n")
.append(" }").append("\n")
- .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(document."+source.getForm().getID()+".name));").append("\n")
+ .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(findObj('"+source.getForm().getID()+"').name));").append("\n")
.append(" return false;").append("\n")
.append("}").append("\n");
if (getAssociatedScript() != null) {
getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString());
}
}
private void addIFrame() {
IFrame iframe = new IFrame(iframeName);
iframe.setID(iframeName);
iframe.setHeight(0);
iframe.setWidth(0);
iframe.setBorder(0);
iframe.setSrc("blank.html");
add(iframe);
}
private void addBuildQueryScript() {
StringBuffer params = new StringBuffer();
params.append("&").append(PARAMETER_SOURCE_PARAMETER_NAME).append("=").append(source.getName());
Set parNames = parameters.keySet();
Iterator iter = parNames.iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
String value = (String) parameters.get(name);
params.append("&").append(name).append("=").append(value);
}
if (getAssociatedScript() != null) {
getAssociatedScript().addFunction("buildQueryString_"+source.getID()+"(theFormName)", "function buildQueryString_"+source.getID()+"(theFormName){ \n"
+" theForm = document.forms[theFormName];\n"
+" var qs = ''\n"
+" for (e=0;e<theForm.elements.length;e++) {\n"
+" if (theForm.elements[e].name != '') {\n"
+" qs+='&'\n"
+" qs+=theForm.elements[e].name+'='+theForm.elements[e].value\n"
// +" qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value)\n"
+" }\n"
+" } \n"
+" qs+='"+params.toString()+"';"
+" return qs\n"
+"}\n");
}
}
private void addScriptForDropdown() {
StringBuffer buff = new StringBuffer();
buff.append("function handleResponse_"+source.getID()+"(doc) {\n")
.append(" var namesEl = document.getElementById('"+source.getID()+"');\n")
.append(" var zipEl = document.getElementById('"+target.getID()+"');\n")
.append(" zipEl.options.length = 0; \n")
.append(" var dataElID = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName(), "id")+"');\n")
.append(" var dataElName = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName(), "name")+"');\n")
.append(" namesColl = dataElName.childNodes; \n")
.append(" idsColl = dataElID.childNodes; \n")
.append(" var numNames = namesColl.length; \n")
.append(" var str = '';\n")
.append(" var ids = '';\n")
.append(" for (var q=0; q<numNames; q++) {\n")
.append(" if (namesColl[q].nodeType!=1) continue; // it's not an element node, let's skedaddle\n")
.append(" str = namesColl[q].name;\n")
.append(" ids = idsColl[q].name;\n")
.append(" zipEl.options[zipEl.options.length] = new Option(str, ids);\n")
.append(" }\n");
buff = addClearMethods(buff);
buff.append("}\n");
getAssociatedScript().addFunction("handleResponse_"+source.getID(), buff.toString());
}
private void addScriptForLayer() {
StringBuffer buff = new StringBuffer();
buff.append("function handleResponse_"+source.getID()+"(doc) {\n")
.append(" var dataEl = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName())+"');\n")
.append(" var str = '';\n")
.append(" if (dataEl != null) {\n")
.append(" namesColl = dataEl.childNodes; \n")
.append(" var numNames = namesColl.length; \n")
.append(" for (var q=0; q<numNames; q++) {\n")
.append(" if (namesColl[q].nodeType!=1) continue; // it's not an element node, let's skedaddle\n")
.append(" str+= namesColl[q].name;\n")
.append(" }\n")
.append(" } else {\n")
.append(" str = '';\n")
.append(" }\n")
.append(" var resultText = this.document.getElementById('"+target.getID()+"');\n")
.append(" resultText.innerHTML = str;\n");
buff = addClearMethods(buff);
buff.append("}\n");
Script s = getAssociatedScript();
if (s != null) {
s.addFunction("handleResponse_"+source.getID(), buff.toString());
}
}
private StringBuffer addClearMethods(StringBuffer script) {
Set keySet = toClear.keySet();
Iterator iter = keySet.iterator();
PresentationObject po;
String value;
while (iter.hasNext()) {
po = (InterfaceObject) iter.next();
value = (String) toClear.get(po);
if (po instanceof DropdownMenu) {
script.append(
" var zipEl = document.getElementById('"+po.getID()+"');\n"+
" zipEl.options.length = 0; \n" +
" zipEl.options[zipEl.options.length] = new Option('"+value+"', '-1');\n");
} else if (po instanceof Layer) {
if (value == null) {
value = "";
}
script.append(
" var resultText = this.document.getElementById('"+po.getID()+"');\n"+
" resultText.innerHTML = '"+value+"';\n");
} else {
throw new IllegalArgumentException("Unsupported target instance "+target.getClass().getName());
}
}
return script;
}
private void handleRemoteCall(IWContext iwc) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String rscClassName = iwc.getParameter(PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS);
RemoteScriptCollection rsc = (RemoteScriptCollection) RefactorClassRegistry.forName(rscClassName).newInstance();
this.getParentPage().setOnLoad("if (parent != self) parent.handleResponse_"+iwc.getParameter(PARAMETER_SOURCE_NAME)+"(document)");
add(rsc.getResults(iwc));
}
private String getRemoteUrl(IWContext iwc) {
String url = iwc.getIWMainApplication().getObjectInstanciatorURI(getClass().getName());
if (url.indexOf("?") < 0) {
url += "?";
}
url += PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS+"="+remoteScriptCollection.getClass().getName()+"&"+PARAMETER_SOURCE_NAME+"="+source.getID();
return url;
}
private boolean isRemoteCall(IWContext iwc) {
return iwc.isParameterSet(PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS);
}
/**
* Method to get the name of a layer
* @param sourceName The name of the source object
* @return
*/
public static String getLayerName(String sourceName) {
return sourceName+"_div";
}
/**
* Method to get the name of a layer
* @param sourceName The name of the source object
* @param addon A string to add to the name, e.g. <code>id</code> or <code>name</code>
* @return
*/
public static String getLayerName(String sourceName, String addon) {
return sourceName+"_"+addon+"_div";
}
/**
* Method to get the event to trigger the remote script, can be used with onChange, onBlur, and so on.
* @param iwc IWContext
* @return
*/
public String getSubmitEvent(IWContext iwc) {
return "return callToServer_"+iframeName+"(findObj('"+source.getForm().getID()+"').name)";
}
/**
* Set which class handles the remote procedure
* Class must implement RemoteScripCollection class
* @param remoteScriptCollectionClass
* @throws InstantiationException
* @throws IllegalAccessException
*/
public void setRemoteScriptCollectionClass(Class remoteScriptCollectionClass) throws InstantiationException, IllegalAccessException {
this.remoteScriptCollection = (RemoteScriptCollection) remoteScriptCollectionClass.newInstance();
}
/**
* Set wether or not the source object triggers the event.
* Default value is <code>true</code>
* @param isSourceTrigger
*/
public void setIsSourceTrigger(boolean isSourceTrigger) {
this.sourceIsTrigger = isSourceTrigger;
}
/**
* Add a parameter that is submitted to the remote page
* @param name Name of the parameter
* @param value Value of the parameter
*/
public void addParameter(String name, String value) {
parameters.put(name, value);
}
/**
* Set if the event is supposed to clear an object
* @param po PresentationObject that is to be cleared
* @param emptyValue A value to use instead of nothing
*/
public void setToClear(PresentationObject po, String emptyValue) {
toClear.put(po, emptyValue);
}
}
| true | true | private void addCallToServer(IWContext iwc) {
StringBuffer buff = new StringBuffer();
buff.append("var IFrameObj; // our IFrame object").append("\n")
.append("function callToServer_"+iframeName+"(theFormName) {").append("\n")
.append(" if (!document.createElement) {return true};").append("\n")
.append(" var IFrameDoc;").append("\n")
.append(" if (!IFrameObj && document.createElement) {").append("\n")
.append(" // create the IFrame and assign a reference to the").append("\n")
.append(" // object to our global variable IFrameObj.").append("\n")
.append(" // this will only happen the first time") .append("\n")
.append(" // callToServer() is called").append("\n")
.append(" try {").append("\n")
.append(" var tempIFrame=document.createElement('iframe');").append("\n")
.append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n")
.append(" tempIFrame.style.border='0px';").append("\n")
.append(" tempIFrame.style.width='0px';").append("\n")
.append(" tempIFrame.style.height='0px';").append("\n")
.append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n")
.append(" if (document.frames) {").append("\n")
.append(" // this is for IE5 Mac, because it will only").append("\n")
.append(" // allow access to the document object").append("\n")
.append(" // of the IFrame if we access it through").append("\n")
.append(" // the document.frames array").append("\n")
.append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n")
.append(" }").append("\n")
.append(" } catch(exception) {").append("\n")
.append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n")
.append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n")
.append(" // it up by creating our own objects.").append("\n")
.append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n")
.append(" iframeHTML+='border:0px;';").append("\n")
.append(" iframeHTML+='width:0px;';").append("\n")
.append(" iframeHTML+='height:0px;';").append("\n")
.append(" iframeHTML+='\"><\\/iframe>';").append("\n")
.append(" document.body.innerHTML+=iframeHTML;").append("\n")
.append(" IFrameObj = new Object();").append("\n")
.append(" IFrameObj.document = new Object();").append("\n")
.append(" IFrameObj.document.location = new Object();").append("\n")
.append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n")
.append(" IFrameObj.document.location.replace = function(location) {").append("\n")
.append(" this.iframe.src = location;").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n")
.append(" // we have to give NS6 a fraction of a second").append("\n")
.append(" // to recognize the new IFrame").append("\n")
.append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n")
.append(" return false;").append("\n")
.append(" }").append("\n")
.append(" if (IFrameObj.contentDocument) {").append("\n")
.append(" // For NS6").append("\n")
.append(" IFrameDoc = IFrameObj.contentDocument;").append("\n")
.append(" } else if (IFrameObj.contentWindow) {").append("\n")
.append(" // For IE5.5 and IE6").append("\n")
.append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n")
.append(" } else if (IFrameObj.document) {").append("\n")
.append(" // For IE5").append("\n")
.append(" IFrameDoc = IFrameObj.document;").append("\n")
.append(" } else {").append("\n")
.append(" return true;").append("\n")
.append(" }").append("\n")
.append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(document."+source.getForm().getID()+".name));").append("\n")
.append(" return false;").append("\n")
.append("}").append("\n");
if (getAssociatedScript() != null) {
getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString());
}
}
| private void addCallToServer(IWContext iwc) {
StringBuffer buff = new StringBuffer();
buff.append("var IFrameObj; // our IFrame object").append("\n")
.append("function callToServer_"+iframeName+"(theFormName) {").append("\n")
.append(" if (!document.createElement) {return true};").append("\n")
.append(" var IFrameDoc;").append("\n")
.append(" if (!IFrameObj && document.createElement) {").append("\n")
.append(" // create the IFrame and assign a reference to the").append("\n")
.append(" // object to our global variable IFrameObj.").append("\n")
.append(" // this will only happen the first time") .append("\n")
.append(" // callToServer() is called").append("\n")
.append(" try {").append("\n")
.append(" var tempIFrame=document.createElement('iframe');").append("\n")
.append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n")
.append(" tempIFrame.style.border='0px';").append("\n")
.append(" tempIFrame.style.width='0px';").append("\n")
.append(" tempIFrame.style.height='0px';").append("\n")
.append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n")
.append(" if (document.frames) {").append("\n")
.append(" // this is for IE5 Mac, because it will only").append("\n")
.append(" // allow access to the document object").append("\n")
.append(" // of the IFrame if we access it through").append("\n")
.append(" // the document.frames array").append("\n")
.append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n")
.append(" }").append("\n")
.append(" } catch(exception) {").append("\n")
.append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n")
.append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n")
.append(" // it up by creating our own objects.").append("\n")
.append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n")
.append(" iframeHTML+='border:0px;';").append("\n")
.append(" iframeHTML+='width:0px;';").append("\n")
.append(" iframeHTML+='height:0px;';").append("\n")
.append(" iframeHTML+='\"><\\/iframe>';").append("\n")
.append(" document.body.innerHTML+=iframeHTML;").append("\n")
.append(" IFrameObj = new Object();").append("\n")
.append(" IFrameObj.document = new Object();").append("\n")
.append(" IFrameObj.document.location = new Object();").append("\n")
.append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n")
.append(" IFrameObj.document.location.replace = function(location) {").append("\n")
.append(" this.iframe.src = location;").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" }").append("\n")
.append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n")
.append(" // we have to give NS6 a fraction of a second").append("\n")
.append(" // to recognize the new IFrame").append("\n")
.append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n")
.append(" return false;").append("\n")
.append(" }").append("\n")
.append(" if (IFrameObj.contentDocument) {").append("\n")
.append(" // For NS6").append("\n")
.append(" IFrameDoc = IFrameObj.contentDocument;").append("\n")
.append(" } else if (IFrameObj.contentWindow) {").append("\n")
.append(" // For IE5.5 and IE6").append("\n")
.append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n")
.append(" } else if (IFrameObj.document) {").append("\n")
.append(" // For IE5").append("\n")
.append(" IFrameDoc = IFrameObj.document;").append("\n")
.append(" } else {").append("\n")
.append(" return true;").append("\n")
.append(" }").append("\n")
.append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(findObj('"+source.getForm().getID()+"').name));").append("\n")
.append(" return false;").append("\n")
.append("}").append("\n");
if (getAssociatedScript() != null) {
getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString());
}
}
|
diff --git a/src/modelo/DescuentoServicios.java b/src/modelo/DescuentoServicios.java
index 7133447..2fea307 100644
--- a/src/modelo/DescuentoServicios.java
+++ b/src/modelo/DescuentoServicios.java
@@ -1,36 +1,36 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
import java.util.ArrayList;
/**
*
* @author HP
*/
public class DescuentoServicios extends SueldoDecorador{
ArrayList<Servicio> servicios;
private double descuentoPorServicios;
public DescuentoServicios(String idEmpleado, Sueldo sueldoDecorado)
{
this.idEmpleado = idEmpleado;
this.sueldoDecorado = sueldoDecorado;
}
public double calcularDescuentoPorServicios()
{
double descuento = 0.0;
for (int i = 0; i < servicios.size(); i++) {
descuento += servicios.get(i).getMonto();
}
- return 0.0;
+ return descuento;
}
public double calcularSueldo() {
return sueldoDecorado.calcularSueldo()- descuentoPorServicios;
}
}
| true | true | public double calcularDescuentoPorServicios()
{
double descuento = 0.0;
for (int i = 0; i < servicios.size(); i++) {
descuento += servicios.get(i).getMonto();
}
return 0.0;
}
| public double calcularDescuentoPorServicios()
{
double descuento = 0.0;
for (int i = 0; i < servicios.size(); i++) {
descuento += servicios.get(i).getMonto();
}
return descuento;
}
|
diff --git a/src/com/themagpi/activities/MagpiMainActivity.java b/src/com/themagpi/activities/MagpiMainActivity.java
index 5b589f3..4a4f155 100644
--- a/src/com/themagpi/activities/MagpiMainActivity.java
+++ b/src/com/themagpi/activities/MagpiMainActivity.java
@@ -1,170 +1,174 @@
package com.themagpi.activities;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.google.android.gcm.GCMRegistrar;
import com.themagpi.adapters.PagerAdapter;
import com.themagpi.android.CompatActionBarNavHandler;
import com.themagpi.android.CompatActionBarNavListener;
import com.themagpi.android.Config;
import com.themagpi.android.R;
import com.themagpi.api.MagPiClient;
import com.themagpi.fragments.IssuesFragment;
import com.themagpi.fragments.NewsFragment;
import com.themagpi.interfaces.Refreshable;
import com.themagpi.interfaces.RefreshableContainer;
public class MagpiMainActivity extends SherlockFragmentActivity
implements ViewPager.OnPageChangeListener , CompatActionBarNavListener, RefreshableContainer {
OnNavigationListener mOnNavigationListener;
SherlockFragment currentFragment;
private PagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private Menu menu;
private LayoutInflater inflater;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getSupportMenuInflater().inflate(R.menu.activity_magpi, menu);
this.inflater = (LayoutInflater) ((SherlockFragmentActivity) this).getSupportActionBar().getThemedContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return true;
}
private void intialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, IssuesFragment.class.getName()));
fragments.add(Fragment.instantiate(this, NewsFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item)
{
switch(item.getItemId()) {
case R.id.menu_refresh:
refreshFragment((Refreshable)this.mPagerAdapter.getItem(mViewPager.getCurrentItem()));
break;
case R.id.menu_settings:
Intent intent = new Intent(this, MagpiSettingsActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
public void refreshFragment(Refreshable fragment) {
if(fragment != null)
fragment.refresh();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magpi_main);
- GCMRegistrar.checkDevice(this);
- GCMRegistrar.checkManifest(this);
- final String idGcm = GCMRegistrar.getRegistrationId(this);
- if (TextUtils.isEmpty(idGcm)) {
- Log.e("GCM", "NOT registered");
- GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID);
- } else {
- Log.e("GCM", "Already registered" + idGcm);
- if(isTimeToRegister())
- new MagPiClient().registerDevice(this, idGcm);
- }
+ try {
+ GCMRegistrar.checkDevice(this);
+ GCMRegistrar.checkManifest(this);
+ final String idGcm = GCMRegistrar.getRegistrationId(this);
+ if (TextUtils.isEmpty(idGcm)) {
+ Log.e("GCM", "NOT registered");
+ GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID);
+ } else {
+ Log.e("GCM", "Already registered" + idGcm);
+ if(isTimeToRegister())
+ new MagPiClient().registerDevice(this, idGcm);
+ }
+ } catch (UnsupportedOperationException ex) {
+ Log.e("GCM", "Google Cloud Messaging not supported - please install Google Apps package!");
+ }
mOnNavigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
return true;
}
};
this.intialiseViewPager();
CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array,
android.R.layout.simple_spinner_dropdown_item);
getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array);
for (int i = 0; i < CATEGORIES.length; i++) {
this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText(
CATEGORIES[i]).setTabListener(handler));
}
getSupportActionBar().setSelectedNavigationItem(0);
}
private boolean isTimeToRegister() {
SharedPreferences prefs = this.getSharedPreferences("MAGPI_REGISTRATION", Context.MODE_PRIVATE);
long timeLastRegistration = prefs.getLong("TIME_LAST_REG", 0L);
long currentTime = Calendar.getInstance().getTimeInMillis();
Log.e("NOW", ""+ currentTime);
Log.e("LAST",""+timeLastRegistration);
if(currentTime > timeLastRegistration + 86400000L)
return true;
return false;
}
@Override
public void onCategorySelected(int catIndex) {
this.mViewPager.setCurrentItem(catIndex);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int pos) {
getSupportActionBar().setSelectedNavigationItem(pos);
}
@Override
public void startRefreshIndicator() {
if(menu != null)
menu.findItem(R.id.menu_refresh).setActionView(inflater.inflate(R.layout.actionbar_refresh_progress, null));
}
@Override
public void stopRefreshIndicator() {
if(menu != null)
menu.findItem(R.id.menu_refresh).setActionView(null);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magpi_main);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String idGcm = GCMRegistrar.getRegistrationId(this);
if (TextUtils.isEmpty(idGcm)) {
Log.e("GCM", "NOT registered");
GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID);
} else {
Log.e("GCM", "Already registered" + idGcm);
if(isTimeToRegister())
new MagPiClient().registerDevice(this, idGcm);
}
mOnNavigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
return true;
}
};
this.intialiseViewPager();
CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array,
android.R.layout.simple_spinner_dropdown_item);
getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array);
for (int i = 0; i < CATEGORIES.length; i++) {
this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText(
CATEGORIES[i]).setTabListener(handler));
}
getSupportActionBar().setSelectedNavigationItem(0);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magpi_main);
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String idGcm = GCMRegistrar.getRegistrationId(this);
if (TextUtils.isEmpty(idGcm)) {
Log.e("GCM", "NOT registered");
GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID);
} else {
Log.e("GCM", "Already registered" + idGcm);
if(isTimeToRegister())
new MagPiClient().registerDevice(this, idGcm);
}
} catch (UnsupportedOperationException ex) {
Log.e("GCM", "Google Cloud Messaging not supported - please install Google Apps package!");
}
mOnNavigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
return true;
}
};
this.intialiseViewPager();
CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array,
android.R.layout.simple_spinner_dropdown_item);
getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array);
for (int i = 0; i < CATEGORIES.length; i++) {
this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText(
CATEGORIES[i]).setTabListener(handler));
}
getSupportActionBar().setSelectedNavigationItem(0);
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java
index 867b820d8..cf0625e9a 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java
@@ -1,183 +1,183 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// 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.puppycrawl.tools.checkstyle;
import java.io.Serializable;
import java.io.ObjectStreamException;
import java.util.Map;
import java.util.HashMap;
/**
* Represents a Java visibility scope.
*
* @author <a href="mailto:lkuehne@users.sourceforge.net">Lars K�hne</a>
*/
public final class Scope implements Comparable, Serializable
{
// Note that although this class might seem to be an
// implementation detail, this class has to be public because it
// is used as a parameter in Configuration.setJavadocScope()
/** poor man's enum for nothing scope */
private static final int SCOPECODE_NOTHING = 0;
/** poor man's enum for public scope */
private static final int SCOPECODE_PUBLIC = 1;
/** poor man's enum for protected scope */
private static final int SCOPECODE_PROTECTED = 2;
/** poor man's enum for package scope */
private static final int SCOPECODE_PACKAGE = 3;
/** poor man's enum for private scope */
private static final int SCOPECODE_PRIVATE = 4;
/** poor man's enum for anonymous inner class scope */
private static final int SCOPECODE_ANONINNER = 5;
/** none scopename */
private static final String SCOPENAME_NOTHING = "nothing";
/** public scopename */
private static final String SCOPENAME_PUBLIC = "public";
/** protected scopename */
private static final String SCOPENAME_PROTECTED = "protected";
/** package scopename */
private static final String SCOPENAME_PACKAGE = "package";
/** private scopename */
private static final String SCOPENAME_PRIVATE = "private";
/** anon inner scopename */
private static final String SCOPENAME_ANONINNER = "anoninner";
/** nothing scope */
static final Scope NOTHING =
new Scope(SCOPECODE_NOTHING, SCOPENAME_NOTHING);
/** public scope */
static final Scope PUBLIC =
new Scope(SCOPECODE_PUBLIC, SCOPENAME_PUBLIC);
/** protected scope */
static final Scope PROTECTED =
new Scope(SCOPECODE_PROTECTED, SCOPENAME_PROTECTED);
/** package scope */
static final Scope PACKAGE =
new Scope(SCOPECODE_PACKAGE, SCOPENAME_PACKAGE);
/** private scope */
static final Scope PRIVATE =
new Scope(SCOPECODE_PRIVATE, SCOPENAME_PRIVATE);
/** anon inner scope */
static final Scope ANONINNER =
new Scope(SCOPECODE_ANONINNER, SCOPENAME_ANONINNER);
/** map from scope names to the respective Scope */
private static final Map NAME_TO_SCOPE = new HashMap();
static {
NAME_TO_SCOPE.put(SCOPENAME_NOTHING, NOTHING);
NAME_TO_SCOPE.put(SCOPENAME_PUBLIC, PUBLIC);
NAME_TO_SCOPE.put(SCOPENAME_PROTECTED, PROTECTED);
NAME_TO_SCOPE.put(SCOPENAME_PACKAGE, PACKAGE);
NAME_TO_SCOPE.put(SCOPENAME_PRIVATE, PRIVATE);
NAME_TO_SCOPE.put(SCOPENAME_ANONINNER, ANONINNER);
};
/** the SCOPECODE_XYZ value of this scope. */
private final int mCode;
/** the name of this scope. */
private final String mName;
/**
* @see Object
*/
public String toString()
{
return "Scope[" + mCode + " (" + mName + ")]";
}
/**
* @return the name of this scope.
*/
String getName()
{
return mName;
}
/**
* @see Comparable
*/
public int compareTo(Object aObject)
{
Scope scope = (Scope) aObject;
return this.mCode - scope.mCode;
}
/**
* Checks if this scope is a subscope of another scope.
* Example: PUBLIC is a subscope of PRIVATE.
*
* @param aScope a <code>Scope</code> value
* @return if <code>this</code> is a subscope of <code>aScope</code>.
*/
boolean isIn(Scope aScope)
{
return (compareTo(aScope) <= 0);
}
/**
* Creates a new <code>Scope</code> instance.
*
* @param aCode one of the SCOPECODE_XYZ values.
* @param aName one of the SCOPENAME_XYZ values.
*/
private Scope(int aCode, String aName)
{
mCode = aCode;
mName = aName;
}
/**
* Scope factory method.
*
* @param aScopeName scope name, such as "nothing", "public", etc.
* @return the <code>Scope</code> associated with <code>aScopeName</code>
*/
static Scope getInstance(String aScopeName)
{
// canonicalize argument
- String scopeName = aScopeName.toLowerCase();
+ final String scopeName = aScopeName.trim().toLowerCase();
final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName);
if (retVal == null) {
throw new IllegalArgumentException(scopeName);
}
return retVal;
}
/**
* Ensures that we don't get multiple instances of one Scope
* during deserialization. See Section 3.6 of the Java Object
* Serialization Specification for details.
*
* @return the serialization replacement object
* @throws ObjectStreamException if a deserialization error occurs
*/
private Object readResolve() throws ObjectStreamException
{
return getInstance(mName);
}
}
| true | true | static Scope getInstance(String aScopeName)
{
// canonicalize argument
String scopeName = aScopeName.toLowerCase();
final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName);
if (retVal == null) {
throw new IllegalArgumentException(scopeName);
}
return retVal;
}
| static Scope getInstance(String aScopeName)
{
// canonicalize argument
final String scopeName = aScopeName.trim().toLowerCase();
final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName);
if (retVal == null) {
throw new IllegalArgumentException(scopeName);
}
return retVal;
}
|
diff --git a/src/InventoryFrame.java b/src/InventoryFrame.java
index 88a256c..ba9816d 100644
--- a/src/InventoryFrame.java
+++ b/src/InventoryFrame.java
@@ -1,152 +1,153 @@
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class InventoryFrame extends JFrame
{
private Player thePlayer;
private JButton use;
private JButton drop;
private JButton back;
private JList inventory;
private JTextArea descriptionArea;
private DefaultListModel inventoryList;
private JScrollPane scroll;
private JPanel buttons;
private JPanel itemPanel;
private JLabel message;
private Vector<Integer> usableItems; // Let Bryant decide what is usable
public InventoryFrame(Player player)
{
super("Inventory");
thePlayer = player;
use = new JButton("Use");
drop = new JButton("Drop");
back = new JButton("Back");
buttons = new JPanel();
ButtonListener handler = new ButtonListener();
use.addActionListener(handler);
drop.addActionListener(handler);
back.addActionListener(handler);
buttons.add(use);
buttons.add(drop);
buttons.add(back);
itemPanel = new JPanel();
descriptionArea = new JTextArea();
descriptionArea.setPreferredSize(new Dimension(200, 200));
+ descriptionArea.setWrapStyleWord(true);
descriptionArea.setLineWrap(true);
descriptionArea.setEditable(false);
usableItems = new Vector<Integer>();
fillUsuable();
message = new JLabel();
makeInventory();
inventory = new JList(inventoryList);
inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inventory.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent arg0)
{
descriptionArea.setText(((Item) inventory.getSelectedValue())
.getDescription());
}
});
scroll = new JScrollPane(inventory);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
itemPanel.add(scroll);
itemPanel.add(descriptionArea);
this.setLayout(new BorderLayout());
this.add(itemPanel, BorderLayout.CENTER);
this.add(buttons, BorderLayout.SOUTH);
this.add(message, BorderLayout.NORTH);
}
/**
* Use this method to fill the array of Items that can be used. If the name of
* the item is not added to this array it won't be able to be used.!!!! Use
* the number that is assigned to each Item
*
*/
private void fillUsuable()
{
usableItems.add(4);
usableItems.add(32);
usableItems.add(31);
usableItems.add(30);
}
private void makeInventory()
{
inventoryList = new DefaultListModel();
Vector<Item> v = thePlayer.getInventory();
for (Item item : v)
{
inventoryList.addElement(item);
}
}
private class ButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent event)
{
Item item = (Item) inventory.getSelectedValue();
int itemNumber = item.getIDNumber();
if (event.getSource().equals(use))
{
if (usableItems.contains(itemNumber))
{
thePlayer.use(item);
message.setText("Fuel increased to: " + thePlayer.getFuelLevel());
} else
{
message.setText("You can't use this item");
}
} else if (event.getSource().equals(drop))
{
thePlayer.drop(item);
}
repaint(); //not working I think it has something to do with the list selection listener.
}
}
}
| true | true | public InventoryFrame(Player player)
{
super("Inventory");
thePlayer = player;
use = new JButton("Use");
drop = new JButton("Drop");
back = new JButton("Back");
buttons = new JPanel();
ButtonListener handler = new ButtonListener();
use.addActionListener(handler);
drop.addActionListener(handler);
back.addActionListener(handler);
buttons.add(use);
buttons.add(drop);
buttons.add(back);
itemPanel = new JPanel();
descriptionArea = new JTextArea();
descriptionArea.setPreferredSize(new Dimension(200, 200));
descriptionArea.setLineWrap(true);
descriptionArea.setEditable(false);
usableItems = new Vector<Integer>();
fillUsuable();
message = new JLabel();
makeInventory();
inventory = new JList(inventoryList);
inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inventory.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent arg0)
{
descriptionArea.setText(((Item) inventory.getSelectedValue())
.getDescription());
}
});
scroll = new JScrollPane(inventory);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
itemPanel.add(scroll);
itemPanel.add(descriptionArea);
this.setLayout(new BorderLayout());
this.add(itemPanel, BorderLayout.CENTER);
this.add(buttons, BorderLayout.SOUTH);
this.add(message, BorderLayout.NORTH);
}
| public InventoryFrame(Player player)
{
super("Inventory");
thePlayer = player;
use = new JButton("Use");
drop = new JButton("Drop");
back = new JButton("Back");
buttons = new JPanel();
ButtonListener handler = new ButtonListener();
use.addActionListener(handler);
drop.addActionListener(handler);
back.addActionListener(handler);
buttons.add(use);
buttons.add(drop);
buttons.add(back);
itemPanel = new JPanel();
descriptionArea = new JTextArea();
descriptionArea.setPreferredSize(new Dimension(200, 200));
descriptionArea.setWrapStyleWord(true);
descriptionArea.setLineWrap(true);
descriptionArea.setEditable(false);
usableItems = new Vector<Integer>();
fillUsuable();
message = new JLabel();
makeInventory();
inventory = new JList(inventoryList);
inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inventory.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent arg0)
{
descriptionArea.setText(((Item) inventory.getSelectedValue())
.getDescription());
}
});
scroll = new JScrollPane(inventory);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
itemPanel.add(scroll);
itemPanel.add(descriptionArea);
this.setLayout(new BorderLayout());
this.add(itemPanel, BorderLayout.CENTER);
this.add(buttons, BorderLayout.SOUTH);
this.add(message, BorderLayout.NORTH);
}
|
diff --git a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
index d51c9025..81dd8274 100644
--- a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
+++ b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
@@ -1,499 +1,497 @@
package de.hpi.bpmn2execpn.converter;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import de.hpi.bpmn.BPMNDiagram;
import de.hpi.bpmn.DataObject;
import de.hpi.bpmn.ExecDataObject;
import de.hpi.bpmn.Edge;
import de.hpi.bpmn.IntermediateEvent;
import de.hpi.bpmn.SubProcess;
import de.hpi.bpmn.Task;
import de.hpi.bpmn2execpn.model.ExecTask;
import de.hpi.bpmn2pn.converter.Converter;
import de.hpi.bpmn2pn.converter.DataObjectNoInitStateException;
import de.hpi.bpmn2pn.model.ConversionContext;
import de.hpi.bpmn2pn.model.SubProcessPlaces;
import de.hpi.execpn.AutomaticTransition;
import de.hpi.execpn.ExecFlowRelationship;
import de.hpi.execpn.ExecPetriNet;
import de.hpi.execpn.FormTransition;
import de.hpi.execpn.impl.ExecPNFactoryImpl;
import de.hpi.execpn.pnml.Locator;
import de.hpi.petrinet.PetriNet;
import de.hpi.petrinet.Place;
import de.hpi.petrinet.Transition;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.w3c.dom.ls.*;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
public class ExecConverter extends Converter {
private static final boolean abortWhenFinalize = true;
private static final String baseXsltURL = "http://localhost:3000/examples/contextPlace/";
private static final String copyXsltURL = baseXsltURL + "copy_xslt.xsl";
private static final String extractDataURL = baseXsltURL + "extract_processdata.xsl";
protected String standardModel;
protected String baseFileName;
private List<ExecTask> taskList;
public ExecConverter(BPMNDiagram diagram, String modelURL) {
super(diagram, new ExecPNFactoryImpl(modelURL));
this.standardModel = modelURL;
this.taskList = new ArrayList<ExecTask>();
}
public void setBaseFileName(String basefilename) {
this.baseFileName = basefilename;
}
@Override
protected void handleDiagram(PetriNet net, ConversionContext c) {
((ExecPetriNet) net).setName(diagram.getTitle());
}
@Override
protected void createStartPlaces(PetriNet net, ConversionContext c) {
// do nothing...: we want start transitions instead of start places
}
// TODO this is a dirty hack...
@Override
protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges = task.getIncomingEdges();
for (Edge edge : edges) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// persist model and deliver URL
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer dom3Writer = implLS.createLSSerializer();
LSOutput output=implLS.createLSOutput();
OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
output.setByteStream(outputStream);
dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// TODO with model create formular and bindings
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId());
exTask.pl_running = addPlace(net, "pl_running_" + task.getId());
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId());
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId());
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId());
exTask.pl_context = addPlace(net, "pl_context_" + task.getId());
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
- //TODO: create context_finish.xsl
- exTask.tr_finish =exTask.tr_done = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
+ exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
- /*addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
+ addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
- */
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
@Override
protected void handleSubProcess(PetriNet net, SubProcess process,
ConversionContext c) {
super.handleSubProcess(net, process, c);
if (process.isAdhoc()) {
handleSubProcessAdHoc(net, process, c);
}
}
// TODO: Data dependencies
// TODO missing completion condition concept
protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
// TODO: make AutomaticTransition with functionality to evaluate completion condition
//Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_" + process.getId(), "ad-hoc_cc_" + process.getCompletionCondition());
Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId());
// TODO: make Tau when guards work
Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_" + process.getId(), "ad-hoc_finalize");
// TODO: make Tau when guards work
//Transition resume = addLabeledTransition(net, "ad-hoc_resume_" + process.getId(), "ad-hoc_resume");
Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId());
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// parallel ad-hoc construct with abortion of tasks when completion condition is true -------------------------------
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.tr_enable);
addFlowRelationship(net, enableStarting, exTask.tr_allocate);
addFlowRelationship(net, exTask.tr_allocate, enableStarting);
addFlowRelationship(net, enableFinishing, exTask.tr_finish);
addFlowRelationship(net, exTask.tr_finish, executed);
addFlowRelationship(net, exTask.tr_finish, updatedState);
if (exTask.isSkippable()) {
addFlowRelationship(net, enableStarting, exTask.tr_skip);
addFlowRelationship(net, exTask.tr_skip, enableStarting);
}
// finishing construct(finalize with skip, finish, abort and leave_suspend)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
//TODO: remove ability to abort?
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.pl_running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, enableFinalize, leaveSuspended);
addFlowRelationship(net, exTask.pl_suspended, leaveSuspended);
addFlowRelationship(net, leaveSuspended, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
// parallel ad-hoc construct, running tasks can finish on their own after completion condition is true -------------
throw new NotImplementedException();
}else {
// sequential ad-hoc construct -----------------------------------------------------------------------------------------------
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.tr_enable);
addFlowRelationship(net, synch, exTask.tr_allocate);
addFlowRelationship(net, exTask.tr_finish, executed);
addFlowRelationship(net, exTask.tr_finish, updatedState);
addFlowRelationship(net, executed, defaultEndT);
if (exTask.isSkippable()) {
addFlowRelationship(net, synch, exTask.tr_skip);
}
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
@Override
protected void handleDataObject(PetriNet net, DataObject object, ConversionContext c){
try {
if (object instanceof ExecDataObject) {
ExecDataObject dataobject = (ExecDataObject) object;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
//create data place for Task
Place dataPlace = addPlace(net,"pl_data_"+dataobject.getId());
ExecTask.addDataPlace(dataPlace);
// for data place add locators
String modelXML = dataobject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
Document doc = parser.parse(in);
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataPlace.addLocator(new Locator(
child.getNodeName(),
"xsd:string",
"/data/processdata/"+dataobject.getId()+"/"+child.getNodeName()));
child = child.getNextSibling();
};
}
} catch (Exception io) {
io.printStackTrace();
}
}
public AutomaticTransition addAutomaticTransition(PetriNet net, String id, String label, String action, String xsltURL, boolean triggerManually) {
AutomaticTransition t =((ExecPNFactoryImpl) pnfactory).createAutomaticTransition();
t.setId(id);
t.setLabel(label);
t.setAction(action);
t.setXsltURL(xsltURL);
t.setManuallyTriggered(triggerManually);
net.getTransitions().add(t);
return t;
}
public ExecFlowRelationship addExecFlowRelationship(PetriNet net,
de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) {
if (source == null || target == null)
return null;
ExecFlowRelationship rel = ((ExecPNFactoryImpl) pnfactory).createExecFlowRelationship();
rel.setSource(source);
rel.setTarget(target);
rel.setTransformationURL(xsltURL);
net.getFlowRelationships().add(rel);
return rel;
}
public FormTransition addFormTransition(PetriNet net, String id, String label, String model, String form, String bindings) {
FormTransition t = ((ExecPNFactoryImpl)pnfactory).createFormTransition();
t.setId(id);
t.setLabel(label);
t.setFormURL(form);
t.setBindingsURL(bindings);
t.setModelURL(model);
net.getTransitions().add(t);
return t;
}
}
| false | true | protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges = task.getIncomingEdges();
for (Edge edge : edges) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// persist model and deliver URL
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer dom3Writer = implLS.createLSSerializer();
LSOutput output=implLS.createLSOutput();
OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
output.setByteStream(outputStream);
dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// TODO with model create formular and bindings
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId());
exTask.pl_running = addPlace(net, "pl_running_" + task.getId());
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId());
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId());
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId());
exTask.pl_context = addPlace(net, "pl_context_" + task.getId());
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
//TODO: create context_finish.xsl
exTask.tr_finish =exTask.tr_done = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
/*addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
*/
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
| protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges = task.getIncomingEdges();
for (Edge edge : edges) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// persist model and deliver URL
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer dom3Writer = implLS.createLSSerializer();
LSOutput output=implLS.createLSOutput();
OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
output.setByteStream(outputStream);
dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// TODO with model create formular and bindings
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId());
exTask.pl_running = addPlace(net, "pl_running_" + task.getId());
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId());
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId());
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId());
exTask.pl_context = addPlace(net, "pl_context_" + task.getId());
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false);
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
|
diff --git a/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java b/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
index 870fa7a..2b473a4 100755
--- a/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
+++ b/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
@@ -1,90 +1,94 @@
package com.rapidftr.utilities;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
public class ImageUtility {
public static Bitmap scaleImage(EncodedImage encodedImage,
int requiredWidth, int requiredHeight) {
int currentWidth = Fixed32.toFP(encodedImage.getWidth());
int currentHeight = Fixed32.toFP(encodedImage.getHeight());
int scaleXFixed32 = Fixed32.div(currentWidth, requiredWidth);
int scaleYFixed32 = Fixed32.div(currentHeight, requiredHeight);
EncodedImage image = encodedImage.scaleImage32(scaleXFixed32,
scaleYFixed32);
return image.getBitmap();
}
public static Bitmap resizeBitmap(Bitmap image, int width, int height) {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// Need an array (for RGB, with the size of original image)
int rgb[] = new int[imageWidth * imageHeight];
// Get the RGB array of image into "rgb"
image.getARGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);
// Call to our function and obtain rgb2
int rgb2[] = rescaleArray(rgb, imageWidth, imageHeight, width, height);
// Create an image with that RGB array
Bitmap temp2 = new Bitmap(width, height);
temp2.setARGB(rgb2, 0, width, 0, 0, width, height);
return temp2;
}
private static int[] rescaleArray(int[] ini, int x, int y, int x2, int y2) {
int out[] = new int[x2 * y2];
for (int yy = 0; yy < y2; yy++) {
int dy = yy * y / y2;
for (int xx = 0; xx < x2; xx++) {
int dx = xx * x / x2;
out[(x2 * yy) + xx] = ini[(x * dy) + dx];
}
}
return out;
}
public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
- } catch (IOException e) {
+ }catch (IllegalArgumentException e)
+ {
+ return EncodedImage.getEncodedImageResource("res\\head.png") ;
+ }
+ catch (IOException e) {
e.printStackTrace();
- return null ;
+ return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
return null;
}
}
| false | true | public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
} catch (IOException e) {
e.printStackTrace();
return null ;
}
return null;
}
| public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
}catch (IllegalArgumentException e)
{
return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
catch (IOException e) {
e.printStackTrace();
return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
return null;
}
|
diff --git a/Neljansuora/src/datas/GUI.java b/Neljansuora/src/datas/GUI.java
index 21668f1..4c49a5e 100644
--- a/Neljansuora/src/datas/GUI.java
+++ b/Neljansuora/src/datas/GUI.java
@@ -1,112 +1,112 @@
package datas;
import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.Map.Entry;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.io.*;
public class GUI extends JFrame {
private Controller control;
private int move = 1;
private JPanel panel;
private JPanel frame;
private LinkedHashMap<Integer, JButton> images;
private Image cross;
private Image empty;
private Image circle;
private JButton restart;
private CrossListener listener = new CrossListener();
private JLabel info;
public void registerController(Controller inControl) {
this.control = inControl;
}
public GUI() {
setUp();
}
public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
- info = new JLabel("Nollan Vuoro");
+ info = new JLabel("Ristin Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
public void makeCross(JButton button) {
if (move % 2 == 0) {
int newCircle = control.getAiMove();
images.put(newCircle,new JButton(new ImageIcon(circle)));
control.makeMove(newCircle,2);
info = new JLabel("Ristin vuoro");
refresh();
move++;
} else {
Set<Entry<Integer, JButton>> es = images.entrySet();
Iterator<Entry<Integer, JButton>> ei = es.iterator();
Map.Entry entry;
while (ei.hasNext()) {
entry = ei.next();
if (entry.getValue().equals(button)) {
int newCross = (Integer) entry.getKey();
images.put(newCross, new JButton(new ImageIcon(cross)));
control.makeMove(newCross,1);
info = new JLabel("Nollan vuoro");
refresh();
move++;
}
}
}
}
public void refresh() {
panel = new JPanel(new GridLayout(10, 10));
Set<Entry<Integer, JButton>> es = images.entrySet();
Iterator<Entry<Integer, JButton>> ei = es.iterator();
while (ei.hasNext()) {
panel.add(ei.next().getValue());
}
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setContentPane(frame);
setVisible(true);
}
private class CrossListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
makeCross((JButton) e.getSource());
}
}
}
| true | true | public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
info = new JLabel("Nollan Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
| public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
info = new JLabel("Ristin Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
|
diff --git a/java/target/src/test/testrt/PeriodicUnrel.java b/java/target/src/test/testrt/PeriodicUnrel.java
index 89001151..ea4bb3bb 100644
--- a/java/target/src/test/testrt/PeriodicUnrel.java
+++ b/java/target/src/test/testrt/PeriodicUnrel.java
@@ -1,63 +1,61 @@
package testrt;
import util.*;
import joprt.*;
import com.jopdesign.sys.*;
// use differnet (unrelated) period to find WC Jitter
public class PeriodicUnrel {
static class Busy extends RtThread {
private int c;
Busy(int per, int ch) {
super(5, per);
c = ch;
}
public void run() {
for (;;) {
// Dbg.wr(c);
waitForNextPeriod();
}
}
}
public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
-RtThread.debug();
// sleep
for (;;) {
-// RtThread.debug();
-Dbg.wr('M');
+ Dbg.wr('M');
Timer.wd();
-for (;;) ;
+ for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
}
| false | true | public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
RtThread.debug();
// sleep
for (;;) {
// RtThread.debug();
Dbg.wr('M');
Timer.wd();
for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
| public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
// sleep
for (;;) {
Dbg.wr('M');
Timer.wd();
for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
|
diff --git a/src/main/java/com/thoughtworks/twu/service/OfferService.java b/src/main/java/com/thoughtworks/twu/service/OfferService.java
index 3809a31..1a2ee00 100644
--- a/src/main/java/com/thoughtworks/twu/service/OfferService.java
+++ b/src/main/java/com/thoughtworks/twu/service/OfferService.java
@@ -1,39 +1,39 @@
package com.thoughtworks.twu.service;
import com.thoughtworks.twu.domain.Offer;
import com.thoughtworks.twu.persistence.OfferDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class OfferService implements OfferServiceInterface {
@Autowired
private OfferDao offerDao;
@Override
public Offer getOfferById(String offerId) {
return offerDao.getOfferById(offerId);
}
@Override
public String saveOffer(Offer offer) {
return offerDao.saveOffer(offer);
}
@Override
public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
- List<Offer> reverseList = new ArrayList<>();
+ List<Offer> reverseList = new ArrayList<Offer>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
}
| true | true | public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
List<Offer> reverseList = new ArrayList<>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
| public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
List<Offer> reverseList = new ArrayList<Offer>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
|
diff --git a/src/simpleserver/util/UnicodeReader.java b/src/simpleserver/util/UnicodeReader.java
index 4635709..79505ac 100644
--- a/src/simpleserver/util/UnicodeReader.java
+++ b/src/simpleserver/util/UnicodeReader.java
@@ -1,129 +1,131 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.Reader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
public class UnicodeReader extends Reader {
private static final int BOM_SIZE = 4;
private static LinkedHashMap<String, byte[]> BOMS;
private PushbackInputStream pushbackReader;
private InputStreamReader reader;
private String encoding;
public UnicodeReader(InputStream in) {
this(in, "UTF-8");
}
public UnicodeReader(InputStream in, String encoding) {
pushbackReader = new PushbackInputStream(in, BOM_SIZE);
this.encoding = encoding;
BOMS = new LinkedHashMap<String, byte[]>(5);
BOMS.put("UTF-8", new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
BOMS.put("UTF-32BE", new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF });
BOMS.put("UTF-32LE", new byte[] { (byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00 });
BOMS.put("UTF-16BE", new byte[] { (byte) 0xFE, (byte) 0xFF });
BOMS.put("UTF-16LE", new byte[] { (byte) 0xFF, (byte) 0xFE });
}
public String getEncoding() {
try {
return reader.getEncoding();
} catch (NullPointerException e) {
return null;
}
}
protected void init() throws IOException {
if (reader != null) {
return;
}
processBOM();
}
protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
- Set<String> encodings = BOMS.keySet();
- Iterator<String> itr = encodings.iterator();
- while (itr.hasNext()) {
- String currentEncoding = itr.next();
- byte[] currentBOM = BOMS.get(currentEncoding);
- if (arrayStartsWith(bom, currentBOM)) {
- encoding = currentEncoding;
- unread = currentBOM.length;
- break;
+ if (read > 0) {
+ Set<String> encodings = BOMS.keySet();
+ Iterator<String> itr = encodings.iterator();
+ while (itr.hasNext()) {
+ String currentEncoding = itr.next();
+ byte[] currentBOM = BOMS.get(currentEncoding);
+ if (arrayStartsWith(bom, currentBOM)) {
+ encoding = currentEncoding;
+ unread = currentBOM.length;
+ break;
+ }
}
- }
- if (unread <= 4) {
- pushbackReader.unread(bom, unread, read - unread);
+ if (unread <= BOM_SIZE && unread > 0) {
+ pushbackReader.unread(bom, unread, read - unread);
+ }
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
protected boolean arrayStartsWith(byte[] in, byte[] needleBytes) {
int pos = 0;
boolean found = true;
if (in.length < needleBytes.length) {
return false;
}
for (byte c : needleBytes) {
if (c != in[pos++]) {
found = false;
break;
}
}
return found;
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
}
}
@Override
public int read(char[] buffer, int offset, int length) throws IOException {
init();
return reader.read(buffer, offset, length);
}
}
| false | true | protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
Set<String> encodings = BOMS.keySet();
Iterator<String> itr = encodings.iterator();
while (itr.hasNext()) {
String currentEncoding = itr.next();
byte[] currentBOM = BOMS.get(currentEncoding);
if (arrayStartsWith(bom, currentBOM)) {
encoding = currentEncoding;
unread = currentBOM.length;
break;
}
}
if (unread <= 4) {
pushbackReader.unread(bom, unread, read - unread);
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
| protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
if (read > 0) {
Set<String> encodings = BOMS.keySet();
Iterator<String> itr = encodings.iterator();
while (itr.hasNext()) {
String currentEncoding = itr.next();
byte[] currentBOM = BOMS.get(currentEncoding);
if (arrayStartsWith(bom, currentBOM)) {
encoding = currentEncoding;
unread = currentBOM.length;
break;
}
}
if (unread <= BOM_SIZE && unread > 0) {
pushbackReader.unread(bom, unread, read - unread);
}
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
|
diff --git a/jsyslogd/src/com/github/picologger/syslog/Parser.java b/jsyslogd/src/com/github/picologger/syslog/Parser.java
index 8ffb1cf..0ee18a8 100644
--- a/jsyslogd/src/com/github/picologger/syslog/Parser.java
+++ b/jsyslogd/src/com/github/picologger/syslog/Parser.java
@@ -1,116 +1,116 @@
/*
* Copyright (C) 2011 cybertk
*
* -- https://github.com/kyan-he/picologger/raw/master/jsyslogd/src/com/github/picologger/syslog/Parser.java--
*
* 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.github.picologger.syslog;
public abstract class Parser
{
public static Syslog parse(String record) throws IllegalArgumentException
{
- if (null == record)
+ if (null == record || "".equals(record))
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
}
| true | true | public static Syslog parse(String record) throws IllegalArgumentException
{
if (null == record)
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
| public static Syslog parse(String record) throws IllegalArgumentException
{
if (null == record || "".equals(record))
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
|
diff --git a/src/main/java/servlet/TestLampServlet.java b/src/main/java/servlet/TestLampServlet.java
index c66296c..a86f3f9 100644
--- a/src/main/java/servlet/TestLampServlet.java
+++ b/src/main/java/servlet/TestLampServlet.java
@@ -1,99 +1,99 @@
package main.java.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class TestLampServlet extends HttpServlet {
// Database Connection
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String convertIntToStatus(int data_value_int) {
// Convert int to string
String status_str = "on";
if (data_value_int == 0) {
status_str = "off";
}
return status_str;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("data_value", rs.getInt(1) );
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-get.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
- ResultSet rs = stmt.executeUpdate("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
+ ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
};
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeUpdate("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
|
diff --git a/ScoreDeviationGroupingToCSV.java b/ScoreDeviationGroupingToCSV.java
index 2bf181d..30f50a4 100755
--- a/ScoreDeviationGroupingToCSV.java
+++ b/ScoreDeviationGroupingToCSV.java
@@ -1,755 +1,755 @@
/*
* Parsing .dev (performance features), .xml (score features) and .apex.xml (structural info)
* and making a single .csv
*
* v 0.7
*
* Elements in the csv file:
* 1. Part OK
* 2. Staff OK
* 3. Measure OK
* 4. Key
* 5. Clef
* 6. Beat position(tactus) OK
* 7. Note number OK
* 8. Note Name
* 9. Duration OK
* 10. Time signature OK
* 11. Slur OK
* 12. Expression marks - dynamics OK
* 13. Expression marks - wedge(cresc, dim.) OK
* 14. Expression marks - tempo(ritardando, accel.) OK
* 15. Articulation - staccato, legato, fermata OK
* 16. Arpeggio
* 17. Ornaments
* 18. Attack Time OK
* 19. Release Time OK
* 20. Tempo OK
* 21. Tempo Deviation OK
* 22. Dynamics OK
* 23. Grouping (reserved)
*
* Taehun Kim
* Audio Communcation Group, TU Berlin
* April 2012
*/
import jp.crestmuse.cmx.commands.*;
import jp.crestmuse.cmx.filewrappers.*;
import java.io.*;
import java.util.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Element;
import javax.xml.parsers.*;
public class ScoreDeviationGroupingToCSV extends CMXCommand {
private Hashtable<String, List> placeholder;
private Hashtable<Integer, Integer> grouping_indicator_dict;
private String scoreFileName;
private String outputFileName;
private String apexFileName;
private String targetDir;
public boolean isMusicXML; // if this is no, input file is .dev
private MusicXMLWrapper musicxml;
private DeviationInstanceWrapper dev;
private void writeToFile() throws IOException {
// get file pointer of the target file
File outFile = new File(outputFileName);
// make a buffer to write a file
java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter(outFile));
writer.write("$score_file: "+ scoreFileName);
writer.newLine();
if (!isMusicXML) {
writer.write("$performance_file: "+ dev.getFileName());
} else {
writer.write("$performance_file: NA");
}
writer.newLine();
// write the header
if (musicxml.hasMovementTitle()) {
writer.write("$title: " + musicxml.getMovementTitle());
writer.newLine();
}
double avg_tempo = -1;
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
writer.write("$avg_tempo: " + avg_tempo);
writer.newLine();
writer.write("$legend: Staff,Voice,Key,Clef,Measure,BeatPos,Metric,Notenum,NoteName,Duration,TimeSig,Slur,DynMark,Wedge,TempoMark,Articulation,Arpeggio,Ornaments,*Attack(0),*Release(1),*Tempo(2),*RelTempo(3),*Velocity(4),*GrpStr_Manual(5)");
writer.newLine();
writer.flush();
// write the body
String buffer[] = new String[placeholder.keySet().size()];
for (Enumeration ks = placeholder.keys(); ks.hasMoreElements();) {
// each key has its xpath. the first element is the position of the note
String xpath = (String)(ks.nextElement());
List aList = placeholder.get(xpath);
int note_position = (Integer)(aList.get(0));
String writeLine = "";
for (int j = 1; j < aList.size(); j++) {
writeLine = writeLine+aList.get(j)+",";
}
writeLine = writeLine.substring(0, writeLine.length() - 1); // remove the last comma (,)
buffer[note_position] = writeLine;
}
for (int i = 0; i < buffer.length; i++) {
System.out.println(buffer[i]);
writer.write(buffer[i]);
writer.newLine();
}
// close file writer
writer.write("-EOF-\n");
writer.flush();
writer.close();
}
private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
- org.w3c.dom.NodeList childNodes = nt.getTheChildNodes();
+ org.w3c.dom.NodeList childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
private void groupingToPlaceholder() {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = null;
try {
document = builder.parse(new FileInputStream(apexFileName));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element rootElement = document.getDocumentElement();
NodeList groups = rootElement.getElementsByTagName(("group"));
for (int i = 0; i < groups.getLength(); i++) {
parseNoteGroupsWithNode(groups.item(i));
}
}
private void parseNoteGroupsWithNode(Node g) {
Element e =(Element)g;
String depth = e.getAttribute("depth");
String grouping_id = getGroupingIdOfDepth(Integer.parseInt(depth));
NodeList notes = g.getChildNodes();
for (int i = 0; i < notes.getLength(); i++) {
// get xpath of the note
if (!(notes.item(i) instanceof Element)) {
continue;
}
Element n = (Element)notes.item(i);
if (n.getTagName().equals("note")) {
String xpath_orig = n.getAttribute("xlink:href");
String xpath = xpath_orig.substring(10, xpath_orig.length()-1);
// find note array with the xpath
List note_array = placeholder.get(xpath);
String grouping = (String)(note_array.get(22)); // 22 is the index of the grouping array
if (grouping.equals("NA")) {
grouping = "";
grouping +=grouping_id;
} else {
grouping = grouping + ":" + grouping_id;
}
note_array.set(22, grouping);
placeholder.remove(xpath);
placeholder.put(xpath, note_array);
} else if (n.getTagName().equals("apex")) {
// Parsing apex info.
// Each group has its own apex point.
// The notes of the apex start will be marked with additional "<"
// The notes of the apex end will be marked with additional ">"
NodeList apex_nodes = n.getChildNodes();
for ( int j = 0; j < apex_nodes.getLength(); j++) {
if (!(apex_nodes.item(j) instanceof Element)) {
continue;
}
Element a = (Element)apex_nodes.item(j);
String xpath_orig = a.getAttribute("xlink:href");
String xpath = xpath_orig.substring(10, xpath_orig.length()-1);
List note_array = placeholder.get(xpath);
System.out.println(note_array);
String grouping = (String)(note_array.get(22)); // 22 is the index of the grouping array
String [] g_split = grouping.split(":");
String target_group = g_split[Integer.parseInt(depth)-1];
if (a.getTagName().equals("start")) {
target_group += "<";
} else if (a.getTagName().equals("stop")) {
target_group += ">";
}
g_split[Integer.parseInt(depth)-1] = target_group;
String newGrouping = "";
for (int m = 0; m < g_split.length; m++) {
newGrouping += g_split[m];
if (m < g_split.length - 1) newGrouping += ":";
}
note_array.set(22, newGrouping);
}
}
}
}
private String getGroupingIdOfDepth(Integer d) {
Integer retVal = -1;
if (grouping_indicator_dict.containsKey(d)) {
Integer value = grouping_indicator_dict.get(d);
Integer newValue = value+1;
grouping_indicator_dict.put(d, newValue);
retVal = newValue;
} else {
// this key is new!
grouping_indicator_dict.put(d, 0);
retVal = 0;
}
return Integer.toString(retVal);
}
protected void run() throws IOException {
if (!isMusicXML) {
dev = (DeviationInstanceWrapper)indata();
//getting target score XML
musicxml = dev.getTargetMusicXML();
// getting score file name and setting output file name
scoreFileName = musicxml.getFileName();
outputFileName = dev.getFileName() + ".apex.csv";
// get apex file name
String [] devFileNameSplit = dev.getFileName().split("\\.(?=[^\\.]+$)");
String devFileNameWithoutExt = devFileNameSplit[0];
String devFileNameWithoutSoundSource;
int string_length = devFileNameWithoutExt.length();
if (devFileNameWithoutExt.charAt(string_length-2) == '-') {
devFileNameWithoutSoundSource = devFileNameWithoutExt.substring(0, string_length-2);
} else {
devFileNameWithoutSoundSource = devFileNameWithoutExt;
}
apexFileName = this.targetDir+devFileNameWithoutSoundSource+".apex.xml";
System.out.println("[LOG] THIS IS DeviationXML FILE.");
System.out.println("[LOG] opening necessary files ...");
System.out.println("ScoreXML: "+scoreFileName+" \nDeviationXML: "+dev.getTargetMusicXMLFileName()+" \nApexXML: "+apexFileName);
System.out.println("OutputCSV: "+outputFileName);
} else {
// this is MusicXML file. so we do not have apex file either!
dev = null;
musicxml = (MusicXMLWrapper)indata();
scoreFileName = musicxml.getFileName();
outputFileName = scoreFileName + ".csv";
System.out.println("[LOG] THIS IS MusicXML FILE.");
System.out.println("[LOG] opening necessary files ...");
System.out.println("ScoreXML: "+scoreFileName);
System.out.println("OutputCSV: "+outputFileName);
}
// Preparing placeholder
placeholder = new Hashtable<String, List>();
// Preparing grouping indicator dicionary
grouping_indicator_dict = new Hashtable<Integer, Integer>();
// Getting score and expressive features from MusicXML into the placeholder
System.out.println("[LOG] parsing score and performance annotations...");
this.scoreDevToPlaceholder();
// Getting structural info form ApexXML into the placeholder
if (!isMusicXML) {
File f = new File(apexFileName);
if (f.exists()) {
System.out.println("[LOG] parsing grouping annotation...");
this.groupingToPlaceholder();
} else {
System.out.println("[LOG] No apex xml is found!");
outputFileName = dev.getFileName()+".csv";
System.out.println("[LOG] new output file name: "+outputFileName);
}
}
// Wrting data in the placeholder into a file
System.out.println("[LOG] writing to the output file...");
this.writeToFile();
}
public static void main(String[] args) {
System.out.println("Score, deviation and grouping annotation parser v 0.7");
System.out.println("Parsing .dev, .xml and .apex.xml and making .csv");
System.out.println("Implemented with CMX API");
System.out.println("Taehun KIM, Audio Communication Group, TU Berlin");
System.out.println("2012");
if (args.length == 0) {
System.out.println("Usage: java ScoreDeviationGroupingToCSV file(s)");
System.out.println("- The input files should have the extension .dev(DeviationXML) or .xml(MusicXML)");
System.exit(1);
}
ScoreDeviationGroupingToCSV c= new ScoreDeviationGroupingToCSV();
// get the target directory
String targetDirArg = args[0];
// check the input file type
c.isMusicXML = targetDirArg.indexOf(".xml") != -1;
String [] split = targetDirArg.split("/");
split[split.length-1] = "";
String result = "";
for (int m = 0; m < split.length; m++) {
result += split[m];
if (m < split.length - 1) result += "/";
}
c.targetDir = result;
try {
c.start(args);
} catch (Exception e) {
c.showErrorMessage(e);
System.exit(1);
}
}
}
| true | true | private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
org.w3c.dom.NodeList childNodes = nt.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
| private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
org.w3c.dom.NodeList childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
|
diff --git a/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java b/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
index cbf1859..9afb057 100644
--- a/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
+++ b/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
@@ -1,111 +1,112 @@
package com.alexrnl.subtitlecorrector.io;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.alexrnl.commons.error.ExceptionUtils;
import com.alexrnl.subtitlecorrector.common.Subtitle;
import com.alexrnl.subtitlecorrector.common.SubtitleFile;
/**
* Abstract class for a subtitle reader.<br />
* @author Alex
*/
public abstract class SubtitleReader {
/** Logger */
private static Logger lg = Logger.getLogger(SubtitleReader.class.getName());
/**
* Constructor #1.<br />
* Default constructor.
*/
public SubtitleReader () {
super();
}
/**
* Read the specified file and return the loaded {@link SubtitleFile}.
* @param file
* the file to read.
* @return the subtitle file, loaded.
* @throws IOException
* if there was a problem while reading the file.
*/
public SubtitleFile readFile (final Path file) throws IOException {
- if (Files.exists(file) || Files.isReadable(file)) {
+ if (!Files.exists(file) || !Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
+ throw new IllegalArgumentException("The file does not exist or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
/**
* Read the header of the subtitle file and build the {@link SubtitleFile} to hold the data.<br />
* May be override by specific subtitle implementations.
* @param file
* the file being read.
* @param reader
* the reader to use.
* @return the subtitle file to use to store the data.
* @throws IOException
* if there was a problem while reading the file.
*/
protected SubtitleFile readHeader (final Path file, final BufferedReader reader) throws IOException {
return new SubtitleFile(file);
}
/**
* Read the footer of the subtitle file.<br />
* May be override by specific implementations.
* @param subtitleFile
* the subtitle file being read.
* @param reader
* the reader to use.
* @throws IOException
* if there was a problem while reading the file.
*/
protected void readFooter (final SubtitleFile subtitleFile, final BufferedReader reader) throws IOException {
// Do nothing
}
/**
* Read a single subtitle of the file.
* @param subtitleFile
* the subtitle file being read.
* @param reader
* the reader to use.
* @return The subtitle read.
* @throws IOException
* if there was a problem while reading the file.
*/
protected abstract Subtitle readSubtitle (final SubtitleFile subtitleFile, final BufferedReader reader) throws IOException;
}
| false | true | public SubtitleFile readFile (final Path file) throws IOException {
if (Files.exists(file) || Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
| public SubtitleFile readFile (final Path file) throws IOException {
if (!Files.exists(file) || !Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
throw new IllegalArgumentException("The file does not exist or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
|
diff --git a/test/sun/misc/Version/Version.java b/test/sun/misc/Version/Version.java
index 6e7d3626d..16ecd1ea9 100644
--- a/test/sun/misc/Version/Version.java
+++ b/test/sun/misc/Version/Version.java
@@ -1,156 +1,162 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6994413
* @summary Check the JDK and JVM version returned by sun.misc.Version
* matches the versions defined in the system properties
* @compile -XDignore.symbol.file Version.java
* @run main Version
*/
import static sun.misc.Version.*;
public class Version {
public static void main(String[] args) throws Exception {
VersionInfo jdk = newVersionInfo(System.getProperty("java.runtime.version"));
VersionInfo v1 = new VersionInfo(jdkMajorVersion(),
jdkMinorVersion(),
jdkMicroVersion(),
jdkUpdateVersion(),
jdkSpecialVersion(),
jdkBuildNumber());
System.out.println("JDK version = " + jdk + " " + v1);
if (!jdk.equals(v1)) {
throw new RuntimeException("Unmatched version: " + jdk + " vs " + v1);
}
VersionInfo jvm = newVersionInfo(System.getProperty("java.vm.version"));
VersionInfo v2 = new VersionInfo(jvmMajorVersion(),
jvmMinorVersion(),
jvmMicroVersion(),
jvmUpdateVersion(),
jvmSpecialVersion(),
jvmBuildNumber());
System.out.println("JVM version = " + jvm + " " + v2);
if (!jvm.equals(v2)) {
throw new RuntimeException("Unmatched version: " + jvm + " vs " + v2);
}
}
static class VersionInfo {
final int major;
final int minor;
final int micro;
final int update;
final String special;
final int build;
VersionInfo(int major, int minor, int micro,
int update, String special, int build) {
this.major = major;
this.minor = minor;
this.micro = micro;
this.update = update;
this.special = special;
this.build = build;
}
public boolean equals(VersionInfo v) {
return (this.major == v.major && this.minor == v.minor &&
this.micro == v.micro && this.update == v.update &&
this.special.equals(v.special) && this.build == v.build);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(major + "." + minor + "." + micro);
if (update > 0) {
sb.append("_" + update);
}
if (!special.isEmpty()) {
sb.append(special);
}
sb.append("-b" + build);
return sb.toString();
}
}
private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
- for (String s : res) {
+ for (int i = res.length - 1; i >= 0; i--) {
+ String s = res[i];
if (s.charAt(0) == 'b') {
- build =
- Integer.valueOf(s.substring(1, s.length())).intValue();
- break;
+ try {
+ build = Integer.parseInt(s.substring(1, s.length()));
+ break;
+ } catch (NumberFormatException nfe) {
+ // ignore
+ }
}
}
}
}
- return new VersionInfo(major, minor, micro, update, special, build);
+ VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
+ System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi);
+ return vi;
}
}
| false | true | private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
for (String s : res) {
if (s.charAt(0) == 'b') {
build =
Integer.valueOf(s.substring(1, s.length())).intValue();
break;
}
}
}
}
return new VersionInfo(major, minor, micro, update, special, build);
}
| private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
for (int i = res.length - 1; i >= 0; i--) {
String s = res[i];
if (s.charAt(0) == 'b') {
try {
build = Integer.parseInt(s.substring(1, s.length()));
break;
} catch (NumberFormatException nfe) {
// ignore
}
}
}
}
}
VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi);
return vi;
}
|
diff --git a/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java b/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
index e3c6387..00cf0a1 100644
--- a/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
+++ b/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
@@ -1,67 +1,67 @@
package edu.cmu.cs.diamond.wholeslide.gui;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import edu.cmu.cs.diamond.wholeslide.Wholeslide;
public class Demo {
public static void main(String[] args) {
- JFrame jf = new JFrame("zzz");
+ JFrame jf = new JFrame("Wholeslide");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
- System.out.println("oops");
+ System.out.println("Give 1 or 2 files");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
- jf.setSize(800, 600);
+ jf.setSize(900, 700);
jf.setVisible(true);
}
}
| false | true | public static void main(String[] args) {
JFrame jf = new JFrame("zzz");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
System.out.println("oops");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
jf.setSize(800, 600);
jf.setVisible(true);
}
| public static void main(String[] args) {
JFrame jf = new JFrame("Wholeslide");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
System.out.println("Give 1 or 2 files");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
jf.setSize(900, 700);
jf.setVisible(true);
}
|
diff --git a/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java b/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
index d3a77b8..613b318 100644
--- a/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
+++ b/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
@@ -1,70 +1,70 @@
/**
*
*/
package org.hitzemann.mms.solver;
import java.util.HashMap;
import java.util.Map;
import org.hitzemann.mms.model.ErgebnisKombination;
import org.hitzemann.mms.model.SpielKombination;
/**
* @author simon
*
*/
public class DefaultErgebnisBerechner implements IErgebnisBerechnung {
/* (non-Javadoc)
* @see org.hitzemann.mms.solver.IErgebnisBerechnung#berechneErgebnis(org.hitzemann.mms.model.SpielKombination, org.hitzemann.mms.model.SpielKombination)
*/
@Override
public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
- if (geheim.getSpielSteineCount() != geraten.getSpielSteineCount()) {
- throw new IllegalArgumentException("Spielsteine haben unterschiedliche Größen!");
+ if (geheim == null || geraten == null || geheim.getSpielSteineCount() != geraten.getSpielSteineCount() ) {
+ throw new IllegalArgumentException();
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
}
| true | true | public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
if (geheim.getSpielSteineCount() != geraten.getSpielSteineCount()) {
throw new IllegalArgumentException("Spielsteine haben unterschiedliche Größen!");
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
| public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
if (geheim == null || geraten == null || geheim.getSpielSteineCount() != geraten.getSpielSteineCount() ) {
throw new IllegalArgumentException();
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
|
diff --git a/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java b/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
index 3f4a0f4e..d0df8912 100644
--- a/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
+++ b/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
@@ -1,415 +1,416 @@
/*
* 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.platform.wizard;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.filechooser.FileView;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.api.java.platform.JavaPlatformManager;
import org.netbeans.modules.javafx.platform.PlatformUiSupport;
import org.openide.modules.InstalledFileLocator;
import org.openide.util.NbBundle;
import org.openide.util.HelpCtx;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileUtil;
import org.openide.util.ChangeSupport;
import org.openide.util.Utilities;
/**
* This Panel launches autoconfiguration during the New JavaFX Platform sequence.
* The UI views properties of the platform, reacts to the end of detection by
* updating itself. It triggers the detection task when the button is pressed.
* The inner class WizardPanel acts as a controller, reacts to the UI completness
* (jdk name filled in) and autoconfig result (passed successfully) - and manages
* Next/Finish button (valid state) according to those.
*
* @author Svata Dedic
*/
public class DetectPanel extends javax.swing.JPanel {
private static final Icon BADGE = new ImageIcon(Utilities.loadImage("org/netbeans/modules/javafx/platform/resources/platformBadge.gif")); // NOI18N
private static final Icon EMPTY = new ImageIcon(Utilities.loadImage("org/netbeans/modules/javafx/platform/resources/empty.gif")); // NOI18N
private final ChangeSupport cs = new ChangeSupport(this);
/**
* Creates a detect panel
* start the task and update on its completion
* @param primaryPlatform the platform being customized.
*/
public DetectPanel() {
initComponents();
postInitComponents ();
putClientProperty("WizardPanel_contentData",
new String[] {
NbBundle.getMessage(DetectPanel.class,"TITLE_PlatformName"),
});
this.setName (NbBundle.getMessage(DetectPanel.class,"TITLE_PlatformName"));
}
public void addNotify() {
super.addNotify();
}
private void postInitComponents () {
DocumentListener lsn = new DocumentListener () {
public void insertUpdate(DocumentEvent e) {
cs.fireChange();
}
public void removeUpdate(DocumentEvent e) {
cs.fireChange();
}
public void changedUpdate(DocumentEvent e) {
cs.fireChange();
}
};
jdkName.getDocument().addDocumentListener(lsn);
fxFolder.getDocument().addDocumentListener(lsn);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
+ jLabel5.setLabelFor(fxFolder);
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
JFileChooser chooser = new JFileChooser ();
final FileSystemView fsv = chooser.getFileSystemView();
chooser.setFileView(new FileView() {
private Icon lastOriginal;
private Icon lastMerged;
public Icon getIcon(File _f) {
File f = FileUtil.normalizeFile(_f);
Icon original = fsv.getSystemIcon(f);
if (original == null) {
// L&F (e.g. GTK) did not specify any icon.
original = EMPTY;
}
if ((new File(f, "bin/javafxpackager.exe").isFile() || new File(f, "bin/javafxpackager").isFile()) && new File(f, "lib/shared/javafxc.jar").isFile() && new File(f, "lib/shared/javafxrt.jar").isFile()) {
if ( original.equals( lastOriginal ) ) {
return lastMerged;
}
lastOriginal = original;
lastMerged = new MergedIcon(original, BADGE, -1, -1);
return lastMerged;
} else {
return original;
}
}
});
FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File f = new File (fxFolder.getText());
chooser.setSelectedFile(f);
chooser.setDialogTitle (NbBundle.getMessage(DetectPanel.class, "TITLE_SelectFX"));
if (chooser.showOpenDialog (this) == JFileChooser.APPROVE_OPTION) {
fxFolder.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_jButton4ActionPerformed
public final synchronized void addChangeListener (ChangeListener listener) {
cs.addChangeListener(listener);
}
public final synchronized void removeChangeListener (ChangeListener listener) {
cs.removeChangeListener(listener);
}
public String getPlatformName() {
return jdkName.getText();
}
public File getPlatformFolder() {
return FileUtil.toFile(JavaPlatformManager.getDefault().getDefaultPlatform().getInstallFolders().iterator().next());
}
public File getFxFolder() {
return FileUtil.normalizeFile(new File(fxFolder.getText()));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField fxFolder;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jdkName;
// End of variables declaration//GEN-END:variables
/**
* Controller for the outer class: manages wizard panel's valid state
* according to the user's input and detection state.
*/
static class WizardPanel implements WizardDescriptor.Panel<WizardDescriptor>,ChangeListener {
private DetectPanel component;
private final JavaFXWizardIterator iterator;
private final ChangeSupport cs = new ChangeSupport(this);
private boolean valid;
private WizardDescriptor wiz;
WizardPanel(JavaFXWizardIterator iterator) {
this.iterator = iterator;
}
public void addChangeListener(ChangeListener l) {
cs.addChangeListener(l);
}
public java.awt.Component getComponent() {
if (component == null) {
component = new DetectPanel();
component.addChangeListener (this);
}
return component;
}
void setValid(boolean v) {
if (v == valid) return;
valid = v;
cs.fireChange();
}
public HelpCtx getHelp() {
return new HelpCtx (DetectPanel.class);
}
public boolean isValid() {
return valid;
}
public void readSettings(WizardDescriptor settings) {
this.wiz = settings;
String name;
int i = 1;
while (!checkName(name = NbBundle.getMessage(DetectPanel.class, "TXT_DefaultPlaformName", String.valueOf(i)))) i++;
component.jdkName.setText(name);
File fxPath = InstalledFileLocator.getDefault().locate("javafx-sdk1.0/lib/shared/javafxc.jar", "org.netbeans.modules.javafx", false);
if (fxPath == null) //try to find runtime in the root javafx folder as for public compiler
fxPath = InstalledFileLocator.getDefault().locate("lib/shared/javafxc.jar", "org.netbeans.modules.javafx", false);
if (fxPath != null && fxPath.isFile()) component.fxFolder.setText(fxPath.getParentFile().getParentFile().getParent());
File f = component.getPlatformFolder();
checkValid();
}
public void removeChangeListener(ChangeListener l) {
cs.removeChangeListener(l);
}
/**
Updates the Platform's display name with the one the user
has entered. Stores user-customized display name into the Platform.
*/
public void storeSettings(WizardDescriptor settings) {
if (isValid()) {
iterator.platformName = component.getPlatformName();
iterator.installFolder = component.getPlatformFolder();
iterator.fxFolder = component.getFxFolder();
}
}
public void stateChanged(ChangeEvent e) {
this.checkValid();
}
private void setErrorMessage(String key) {
this.wiz.putProperty("WizardPanel_errorMessage", NbBundle.getMessage(DetectPanel.class, key)); //NOI18N
setValid(false);
}
private boolean checkName(String name) {
JavaPlatform[] platforms = JavaPlatformManager.getDefault().getInstalledPlatforms();
for (int i=0; i<platforms.length; i++) {
if (name.equals (platforms[i].getDisplayName())) {
setErrorMessage("ERROR_UsedDisplayName"); //NOI18N
return false;
}
}
return true;
}
private void checkValid () {
String name = this.component.getPlatformName ();
if (name.length() == 0) {
setErrorMessage("ERROR_InvalidDisplayName"); //NOI18N
return;
}
if (!checkName(name)) {
setErrorMessage("ERROR_UsedDisplayName"); //NOI18N
return;
}
// File f = component.getPlatformFolder();
// if (!new File(f, "bin/java").isFile() && !new File(f, "bin/java.exe").isFile()) {
// setErrorMessage("ERROR_WrongJavaPlatformLocation"); //NOI18N
// return;
// }
File f = component.getFxFolder();
if (!(new File(f, "bin/javafxpackager.exe").isFile() || new File(f, "bin/javafxpackager").isFile()) || !new File(f, "lib/shared/javafxc.jar").isFile() || !new File(f, "lib/shared/javafxrt.jar").isFile()) {
setErrorMessage("ERROR_WrongFxLocation"); //NOI18N
return;
}
this.wiz.putProperty("WizardPanel_errorMessage", ""); //NOI18N
setValid(true);
}
}
private static class MergedIcon implements Icon {
private Icon icon1;
private Icon icon2;
private int xMerge;
private int yMerge;
MergedIcon( Icon icon1, Icon icon2, int xMerge, int yMerge ) {
this.icon1 = icon1;
this.icon2 = icon2;
if ( xMerge == -1 ) {
xMerge = icon1.getIconWidth() - icon2.getIconWidth();
}
if ( yMerge == -1 ) {
yMerge = icon1.getIconHeight() - icon2.getIconHeight();
}
this.xMerge = xMerge;
this.yMerge = yMerge;
}
public int getIconHeight() {
return Math.max( icon1.getIconHeight(), yMerge + icon2.getIconHeight() );
}
public int getIconWidth() {
return Math.max( icon1.getIconWidth(), yMerge + icon2.getIconWidth() );
}
public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) {
icon1.paintIcon( c, g, x, y );
icon2.paintIcon( c, g, x + xMerge, y + yMerge );
}
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
jLabel5.setLabelFor(fxFolder);
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/zarcode/data/maint/CleanerTask.java b/src/com/zarcode/data/maint/CleanerTask.java
index ec8e6bf..c5c2b9a 100644
--- a/src/com/zarcode/data/maint/CleanerTask.java
+++ b/src/com/zarcode/data/maint/CleanerTask.java
@@ -1,309 +1,309 @@
package com.zarcode.data.maint;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.PhotoEntry;
import com.zarcode.app.AppCommon;
import com.zarcode.common.ApplicationProps;
import com.zarcode.common.EmailHelper;
import com.zarcode.common.Util;
import com.zarcode.data.dao.BuzzDao;
import com.zarcode.data.dao.FeedbackDao;
import com.zarcode.data.dao.PegCounterDao;
import com.zarcode.data.dao.UserDao;
import com.zarcode.data.gdata.PicasaClient;
import com.zarcode.data.model.BuzzMsgDO;
import com.zarcode.data.model.CommentDO;
import com.zarcode.data.model.FeedbackDO;
import com.zarcode.data.model.PegCounterDO;
import com.zarcode.data.model.ReadOnlyUserDO;
import com.zarcode.platform.model.AppPropDO;
public class CleanerTask extends HttpServlet {
private Logger logger = Logger.getLogger(CleanerTask.class.getName());
private StringBuilder report = null;
private static int MAX_DAYS_MESSAGE_IN_SYS = 90;
private static int MAX_DAYS_PEGCOUNTER_IN_SYS = 30;
private static int MAX_DAYS_FEEDBACK_IN_SYS = 30;
private static int MAX_DAYS_ANONYMOUS_USER_IN_SYS = 7;
private static long MSEC_IN_DAY = 86400000;
/**
* Cleans (or deletes) OLD Picasa photos.
* @return
*/
private int cleanPicasaPhotos() {
int i = 0;
int j = 0;
int totalPhotosDeleted = 0;
AlbumEntry album = null;
PhotoEntry photo = null;
List<PhotoEntry> photos = null;
PicasawebService service = new PicasawebService("DockedMobile");
Date createDate = null;
Calendar now = Calendar.getInstance();
long photoLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
int photosDeleted = 0;
try {
PicasaClient client = new PicasaClient(service);
List<AlbumEntry> albums = client.getAlbums();
if (albums != null && albums.size() > 0) {
for (i=0; i<albums.size(); i++) {
album = albums.get(i);
photos = client.getPhotos(album);
if (photos != null && photos.size() > 0) {
photosDeleted = 0;
for (j=0; j<photos.size(); j++) {
photo = photos.get(j);
createDate = photo.getTimestamp();
if (createDate.getTime() < photoLife) {
photo.delete();
photosDeleted++;
totalPhotosDeleted++;
}
}
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return totalPhotosDeleted;
}
/**
* Cleans (or deletes) OLD Anonymous user objects.
*
* @return
*/
private int cleanAnonymousUsers() {
int i = 0;
UserDao userDao = null;
List<ReadOnlyUserDO> tempUsers = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
int anonymousUsersDeleted = 0;
long anonymousUserLife = now.getTimeInMillis() - (MAX_DAYS_ANONYMOUS_USER_IN_SYS * MSEC_IN_DAY);
userDao = new UserDao();
tempUsers = userDao.getAllReadOnlyUsers();
if (tempUsers != null && tempUsers.size() > 0) {
for (i=0; i<tempUsers.size(); i++) {
tempUser = tempUsers.get(i);
if (tempUser.getLastUpdate().getTime() < anonymousUserLife) {
userDao.deleteReadOnlyUser(tempUser);
anonymousUsersDeleted++;
}
}
}
return anonymousUsersDeleted;
}
/**
* Cleans (or deletes) OLD buzz messages.
*
* @return
*/
private int cleanBuzzMsgs() {
int i = 0;
int j = 0;
int buzzMsgsDeleted = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
CommentDO comment = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
try {
eventDao = new BuzzDao();
list = eventDao.getAllMsgs();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
msg = list.get(i);
if (msg.getCreateDate().getTime() < msgLife) {
List<CommentDO> comments = eventDao.getComments4BuzzMsg(msg);
if (comments != null && comments.size() > 0) {
for (j=0; j<comments.size() ; j++) {
comment = comments.get(j);
eventDao.deleteComment(comment);
}
}
eventDao.deleteInstance(msg);
buzzMsgsDeleted++;
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return buzzMsgsDeleted;
}
/**
* Cleans (or deletes) OLD peg counters.
*
* @return
*/
private int cleanPegCounters() {
int i = 0;
int pegCountersDeleted = 0;
PegCounterDao pegDao = null;
UserDao userDao = null;
List<PegCounterDO> list = null;
PegCounterDO peg = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_PEGCOUNTER_IN_SYS * MSEC_IN_DAY);
try {
pegDao = new PegCounterDao();
list = pegDao.getAllPegCounters();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
peg = list.get(i);
if (peg.getLastUpdate().getTime() < msgLife) {
pegDao.deleteInstance(peg);
pegCountersDeleted++;
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return pegCountersDeleted;
}
private List<FeedbackDO> retrieveFeedback() {
int i = 0;
int pegCountersDeleted = 0;
FeedbackDao feedbackDao = null;
UserDao userDao = null;
List<FeedbackDO> list = null;
FeedbackDO feedback = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_PEGCOUNTER_IN_SYS * MSEC_IN_DAY);
try {
feedbackDao = new FeedbackDao();
list = feedbackDao.getAll();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
feedback = list.get(i);
feedbackDao.deleteInstance(feedback);
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return list;
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
|
diff --git a/drools-camel-server/src/main/java/org/drools/server/Test.java b/drools-camel-server/src/main/java/org/drools/server/Test.java
index d4986496c..982ebd997 100644
--- a/drools-camel-server/src/main/java/org/drools/server/Test.java
+++ b/drools-camel-server/src/main/java/org/drools/server/Test.java
@@ -1,78 +1,78 @@
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.camel.CamelContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
String msg = "Hello World";
System.out.println( "Sending Message:\n" + msg);
Test test = new Test();
String response = test.send( msg );
System.out.println( );
System.out.println( );
System.out.println( "Received Response:\n" + response);
}
public String send(String msg) {
- ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:camel-client.xml");
+ ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
public String execute(String msg, CamelContext camelContext) {
String response = camelContext.createProducerTemplate().requestBody( "direct://kservice/rest", msg, String.class );
return response;
}
public String execute(SOAPMessage soapMessage, CamelContext camelContext) throws SOAPException, IOException {
Object object = camelContext.createProducerTemplate().requestBody( "direct://kservice/soap", soapMessage);
OutputStream out = new ByteArrayOutputStream();
SOAPMessage soapResponse = (SOAPMessage) object;
soapResponse.writeTo(out);
return out.toString();
}
}
| true | true | public String send(String msg) {
ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
| public String send(String msg) {
ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
|
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java
index 8784402a8..5d9328e4e 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java
@@ -1,122 +1,122 @@
package org.eclipse.core.internal.resources;
/*
* Licensed Materials - Property of IBM,
* WebSphere Studio Workbench
* (c) Copyright IBM Corp 2000
*/
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.internal.utils.Policy;
public class Folder extends Container implements IFolder {
protected Folder(IPath path, Workspace container) {
super(path, container);
}
/**
* Changes this folder to be a file in the resource tree and returns
* the newly created file. All related
* properties are deleted. It is assumed that on disk the resource is
* already a file so no action is taken to delete the disk contents.
* <p>
* <b>This method is for the exclusive use of the local resource manager</b>
*
* @see FileSystemResourceManager#reportChanges
*/
public IFile changeToFile() throws CoreException {
getPropertyManager().deleteProperties(this);
workspace.deleteResource(this);
IFile result = workspace.getRoot().getFile(path);
workspace.createResource(result, false);
return result;
}
/**
* @see IFolder
*/
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork);
checkValidPath(path, FOLDER);
try {
workspace.prepareOperation();
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkDoesNotExist(flags, false);
workspace.beginOperation(true);
refreshLocal(DEPTH_ZERO, null);
Container parent = (Container) getParent();
info = parent.getResourceInfo(false, false);
flags = getFlags(info);
parent.checkAccessible(flags);
info = getResourceInfo(false, false);
flags = getFlags(info);
if (force) {
if (exists(flags, false))
return;
} else {
checkDoesNotExist(flags, false);
}
- internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork));
+ internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork));
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
/**
* Ensures that this folder exists in the workspace. This is similar in
* concept to mkdirs but it does not work on projects.
* If this folder is created, it will be marked as being local.
*/
public void ensureExists(IProgressMonitor monitor) throws CoreException {
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
if (exists(flags, true))
return;
if (exists(flags, false)) {
String message = Policy.bind("folderOverFile", new String[] { getFullPath().toString()});
throw new ResourceException(IResourceStatus.RESOURCE_WRONG_TYPE, getFullPath(), message, null);
}
Container parent = (Container) getParent();
if (parent.getType() == PROJECT) {
info = parent.getResourceInfo(false, false);
parent.checkExists(getFlags(info), true);
} else
((Folder) parent).ensureExists(monitor);
internalCreate(true, true, monitor);
}
/**
* @see IResource#getType
*/
public int getType() {
return FOLDER;
}
public void internalCreate(boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Creating file.", Policy.totalWork);
workspace.createResource(this, false);
if (local) {
try {
getLocalManager().write(this, force, Policy.subMonitorFor(monitor, Policy.totalWork * 75 / 100));
} catch (CoreException e) {
// a problem happened creating the folder on disk, so delete from the workspace
workspace.deleteResource(this);
throw e; // rethrow
}
}
setLocal(local, DEPTH_ZERO, Policy.subMonitorFor(monitor, Policy.totalWork * 25 / 100));
if (!local)
getResourceInfo(true, true).setModificationStamp(IResource.NULL_STAMP);
} finally {
monitor.done();
}
}
}
| true | true | public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork);
checkValidPath(path, FOLDER);
try {
workspace.prepareOperation();
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkDoesNotExist(flags, false);
workspace.beginOperation(true);
refreshLocal(DEPTH_ZERO, null);
Container parent = (Container) getParent();
info = parent.getResourceInfo(false, false);
flags = getFlags(info);
parent.checkAccessible(flags);
info = getResourceInfo(false, false);
flags = getFlags(info);
if (force) {
if (exists(flags, false))
return;
} else {
checkDoesNotExist(flags, false);
}
internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork));
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
| public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork);
checkValidPath(path, FOLDER);
try {
workspace.prepareOperation();
ResourceInfo info = getResourceInfo(false, false);
int flags = getFlags(info);
checkDoesNotExist(flags, false);
workspace.beginOperation(true);
refreshLocal(DEPTH_ZERO, null);
Container parent = (Container) getParent();
info = parent.getResourceInfo(false, false);
flags = getFlags(info);
parent.checkAccessible(flags);
info = getResourceInfo(false, false);
flags = getFlags(info);
if (force) {
if (exists(flags, false))
return;
} else {
checkDoesNotExist(flags, false);
}
internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork));
} catch (OperationCanceledException e) {
workspace.getWorkManager().operationCanceled();
throw e;
} finally {
workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork));
}
} finally {
monitor.done();
}
}
|
diff --git a/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java b/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java
index a44f4af..1edfe6b 100644
--- a/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java
+++ b/java/osgi/database/src/main/java/com/tintin/devcloud/database/manager/DatabaseManager.java
@@ -1,26 +1,26 @@
package com.tintin.devcloud.database.manager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tintin.devcloud.database.Activator;
import com.tintin.devcloud.database.interfaces.IDatabaseManager;
public class DatabaseManager implements IDatabaseManager {
private Activator activator = null;
private EntityManagerFactory modelEMF = null;
public DatabaseManager(Activator activator) {
this.activator = activator;
- modelEMF = Persistence.createEntityManagerFactory("datamodel");
+ modelEMF = Persistence.createEntityManagerFactory("model");
}
@Override
public EntityManagerFactory getModelEMF() {
return modelEMF;
}
}
| true | true | public DatabaseManager(Activator activator) {
this.activator = activator;
modelEMF = Persistence.createEntityManagerFactory("datamodel");
}
| public DatabaseManager(Activator activator) {
this.activator = activator;
modelEMF = Persistence.createEntityManagerFactory("model");
}
|
diff --git a/src/de/cloudarts/aibattleai/AIContainer.java b/src/de/cloudarts/aibattleai/AIContainer.java
index 8982b3b..7e4d04a 100644
--- a/src/de/cloudarts/aibattleai/AIContainer.java
+++ b/src/de/cloudarts/aibattleai/AIContainer.java
@@ -1,203 +1,203 @@
package de.cloudarts.aibattleai;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import java.util.Scanner;
public class AIContainer {
private static final long SLEEP_MILLIS = 200;
private String _playerName = "Wojtek";
private int _matchID = 0;
private String _token = "";
public AIContainer(String playerName_)
{
if( !playerName_.isEmpty() )
{
_playerName = playerName_;
}
}
public void start()
{
if( !requestNewMatch() )
{
return;
}
// actual game loop
while(true)
{
//get game status
String lastGameStatusAnswerString = requestMatchStatus();
if( isErrorAnswer(lastGameStatusAnswerString) )
{
return;
}
if( isDrawGame(lastGameStatusAnswerString) )
{
return;
}
if( !isItMyTurn(lastGameStatusAnswerString) )
{
//wait a sec, then try again
try
{
Thread.sleep(SLEEP_MILLIS);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
continue;
}
//so it's my turn
// get game status
// compute next action
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Random generator = new Random();
int actionIndex = generator.nextInt(7);
String action = letters[actionIndex];
// send next action
System.out.println("sending action: " + action);
- System.out.println(postAction(action));
+ postAction(action);
// continue in loop
}
}
private Boolean requestNewMatch()
{
URL u = URLCreator.getRequestMatchURL(_playerName);
if (u == null )
{
System.err.println("Error! could not create request url!");
return false;
}
String r = "";
try
{
r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
System.out.println( "requestNewMatch: received answer:" + r );
if( isErrorAnswer(r) )
{
return false;
}
// split answer string in matchID and secret token
String[] temp = r.split(";");
if( temp.length != 2 )
{
System.err.println("requestNewMatch: did expect 2 answer items, but received " + temp.length);
return false;
}
_matchID = Integer.valueOf(temp[0]);
_token = temp[1];
System.out.println("requestNewMatch: received new matchID " + _matchID + " and token " + _token);
return true;
}
private String requestMatchStatus()
{
URL u = URLCreator.getRequestMatchStatusURL(_matchID);
if( u == null )
{
return "error";
}
String r = "";
try
{
r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next();
}
catch (IOException e)
{
e.printStackTrace();
return "error";
}
System.out.println( "requestMatchStatus: received answer:" + r );
return r;
}
private String postAction(String action_)
{
URL u = URLCreator.getPostActionURL(_matchID, _playerName, _token, action_);
if( u == null )
{
return "error";
}
String r = "";
try
{
r = new Scanner( u.openStream() ).useDelimiter( "\\Z" ).next();
}
catch (IOException e)
{
e.printStackTrace();
return "error";
}
System.out.println( "postAction: received answer:" + r );
return r;
}
private Boolean isItMyTurn(String rawStatusString_)
{
String currentTurnPlayer = rawStatusString_.substring(0, _playerName.length());
if( currentTurnPlayer.equals(_playerName) )
{
return true;
}
return false;
}
private Boolean isErrorAnswer(String answer_)
{
if( answer_.substring(0, "error".length()).equals("error") )
{
return true;
}
return false;
}
private boolean isDrawGame(String answer_) {
if( answer_.substring(0, "draw game".length()).equals("draw game") )
{
return true;
}
return false;
}
}
| true | true | public void start()
{
if( !requestNewMatch() )
{
return;
}
// actual game loop
while(true)
{
//get game status
String lastGameStatusAnswerString = requestMatchStatus();
if( isErrorAnswer(lastGameStatusAnswerString) )
{
return;
}
if( isDrawGame(lastGameStatusAnswerString) )
{
return;
}
if( !isItMyTurn(lastGameStatusAnswerString) )
{
//wait a sec, then try again
try
{
Thread.sleep(SLEEP_MILLIS);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
continue;
}
//so it's my turn
// get game status
// compute next action
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Random generator = new Random();
int actionIndex = generator.nextInt(7);
String action = letters[actionIndex];
// send next action
System.out.println("sending action: " + action);
System.out.println(postAction(action));
// continue in loop
}
}
| public void start()
{
if( !requestNewMatch() )
{
return;
}
// actual game loop
while(true)
{
//get game status
String lastGameStatusAnswerString = requestMatchStatus();
if( isErrorAnswer(lastGameStatusAnswerString) )
{
return;
}
if( isDrawGame(lastGameStatusAnswerString) )
{
return;
}
if( !isItMyTurn(lastGameStatusAnswerString) )
{
//wait a sec, then try again
try
{
Thread.sleep(SLEEP_MILLIS);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
continue;
}
//so it's my turn
// get game status
// compute next action
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Random generator = new Random();
int actionIndex = generator.nextInt(7);
String action = letters[actionIndex];
// send next action
System.out.println("sending action: " + action);
postAction(action);
// continue in loop
}
}
|
diff --git a/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java b/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java
index dd90a9c9..b04636e9 100644
--- a/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java
+++ b/de.hswt.hrm.scheme.ui/src/de/hswt/hrm/scheme/ui/TreeManager.java
@@ -1,61 +1,62 @@
package de.hswt.hrm.scheme.ui;
import java.util.HashMap;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import de.hswt.hrm.scheme.model.Category;
import de.hswt.hrm.scheme.model.Direction;
import de.hswt.hrm.scheme.model.RenderedComponent;
import de.hswt.hrm.scheme.model.ThumbnailImage;
/**
* This class manages the TreeItems of a Tree that displays the GridImages.
* The GridImages are organized by their category.
*
* @author Michael Sieger
*
*/
public class TreeManager {
private final IImageTreeModel model;
private final Tree tree;
public TreeManager(IImageTreeModel model, Tree tree) {
super();
this.model = model;
this.tree = tree;
generateTreeItems();
}
private void generateTreeItems(){
tree.clearAll(true);
HashMap<Category, TreeItem> categoryItems = new HashMap<>();
for(RenderedComponent comp : model.getImages()){
Category c = comp.getComponent().getCategory();
TreeItem categoryItem = categoryItems.get(c);
if(categoryItem == null){
categoryItem = new TreeItem(tree, SWT.NONE);
+ categoryItem.setText(c.getName());
categoryItems.put(c, categoryItem);
}
TreeItem item = new TreeItem(categoryItem, SWT.NONE);
- item.setText(c.getName());
+ item.setText(comp.getComponent().getName());
addImage(Direction.downUp, comp, item);
addImage(Direction.upDown, comp, item);
addImage(Direction.leftRight, comp, item);
addImage(Direction.rightLeft, comp, item);
}
}
private void addImage(Direction d, RenderedComponent comp, TreeItem parent){
ThumbnailImage image = comp.getByDirection(d);
if(image != null){
TreeItem item = new TreeItem(parent, SWT.NONE);
item.setImage(image.getThumbnail());
item.setData(new TreeData(comp, d));
}
}
}
| false | true | private void generateTreeItems(){
tree.clearAll(true);
HashMap<Category, TreeItem> categoryItems = new HashMap<>();
for(RenderedComponent comp : model.getImages()){
Category c = comp.getComponent().getCategory();
TreeItem categoryItem = categoryItems.get(c);
if(categoryItem == null){
categoryItem = new TreeItem(tree, SWT.NONE);
categoryItems.put(c, categoryItem);
}
TreeItem item = new TreeItem(categoryItem, SWT.NONE);
item.setText(c.getName());
addImage(Direction.downUp, comp, item);
addImage(Direction.upDown, comp, item);
addImage(Direction.leftRight, comp, item);
addImage(Direction.rightLeft, comp, item);
}
}
| private void generateTreeItems(){
tree.clearAll(true);
HashMap<Category, TreeItem> categoryItems = new HashMap<>();
for(RenderedComponent comp : model.getImages()){
Category c = comp.getComponent().getCategory();
TreeItem categoryItem = categoryItems.get(c);
if(categoryItem == null){
categoryItem = new TreeItem(tree, SWT.NONE);
categoryItem.setText(c.getName());
categoryItems.put(c, categoryItem);
}
TreeItem item = new TreeItem(categoryItem, SWT.NONE);
item.setText(comp.getComponent().getName());
addImage(Direction.downUp, comp, item);
addImage(Direction.upDown, comp, item);
addImage(Direction.leftRight, comp, item);
addImage(Direction.rightLeft, comp, item);
}
}
|
diff --git a/src/nu/validator/htmlparser/impl/TreeBuilder.java b/src/nu/validator/htmlparser/impl/TreeBuilder.java
index f9988d0..5ca303b 100644
--- a/src/nu/validator/htmlparser/impl/TreeBuilder.java
+++ b/src/nu/validator/htmlparser/impl/TreeBuilder.java
@@ -1,5617 +1,5624 @@
/*
* Copyright (c) 2007 Henri Sivonen
* Copyright (c) 2007-2010 Mozilla Foundation
* Portions of comments Copyright 2004-2008 Apple Computer, Inc., Mozilla
* Foundation, and Opera Software ASA.
*
* 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.
*/
/*
* The comments following this one that use the same comment syntax as this
* comment are quotes from the WHATWG HTML 5 spec as of 27 June 2007
* amended as of June 28 2007.
* That document came with this statement:
* "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and
* Opera Software ASA. You are granted a license to use, reproduce and
* create derivative works of this document."
*/
package nu.validator.htmlparser.impl;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nu.validator.htmlparser.annotation.Const;
import nu.validator.htmlparser.annotation.IdType;
import nu.validator.htmlparser.annotation.Inline;
import nu.validator.htmlparser.annotation.Literal;
import nu.validator.htmlparser.annotation.Local;
import nu.validator.htmlparser.annotation.NoLength;
import nu.validator.htmlparser.annotation.NsUri;
import nu.validator.htmlparser.common.DoctypeExpectation;
import nu.validator.htmlparser.common.DocumentMode;
import nu.validator.htmlparser.common.DocumentModeHandler;
import nu.validator.htmlparser.common.Interner;
import nu.validator.htmlparser.common.TokenHandler;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public abstract class TreeBuilder<T> implements TokenHandler,
TreeBuilderState<T> {
/**
* Array version of U+FFFD.
*/
private static final @NoLength char[] REPLACEMENT_CHARACTER = { '\uFFFD' };
// Start dispatch groups
final static int OTHER = 0;
final static int A = 1;
final static int BASE = 2;
final static int BODY = 3;
final static int BR = 4;
final static int BUTTON = 5;
final static int CAPTION = 6;
final static int COL = 7;
final static int COLGROUP = 8;
final static int FORM = 9;
final static int FRAME = 10;
final static int FRAMESET = 11;
final static int IMAGE = 12;
final static int INPUT = 13;
final static int ISINDEX = 14;
final static int LI = 15;
final static int LINK_OR_BASEFONT_OR_BGSOUND = 16;
final static int MATH = 17;
final static int META = 18;
final static int SVG = 19;
final static int HEAD = 20;
final static int HR = 22;
final static int HTML = 23;
final static int NOBR = 24;
final static int NOFRAMES = 25;
final static int NOSCRIPT = 26;
final static int OPTGROUP = 27;
final static int OPTION = 28;
final static int P = 29;
final static int PLAINTEXT = 30;
final static int SCRIPT = 31;
final static int SELECT = 32;
final static int STYLE = 33;
final static int TABLE = 34;
final static int TEXTAREA = 35;
final static int TITLE = 36;
final static int TR = 37;
final static int XMP = 38;
final static int TBODY_OR_THEAD_OR_TFOOT = 39;
final static int TD_OR_TH = 40;
final static int DD_OR_DT = 41;
final static int H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6 = 42;
final static int MARQUEE_OR_APPLET = 43;
final static int PRE_OR_LISTING = 44;
final static int B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U = 45;
final static int UL_OR_OL_OR_DL = 46;
final static int IFRAME = 47;
final static int EMBED_OR_IMG = 48;
final static int AREA_OR_WBR = 49;
final static int DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU = 50;
final static int ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION = 51;
final static int RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR = 52;
final static int RT_OR_RP = 53;
final static int COMMAND = 54;
final static int PARAM_OR_SOURCE = 55;
final static int MGLYPH_OR_MALIGNMARK = 56;
final static int MI_MO_MN_MS_MTEXT = 57;
final static int ANNOTATION_XML = 58;
final static int FOREIGNOBJECT_OR_DESC = 59;
final static int NOEMBED = 60;
final static int FIELDSET = 61;
final static int OUTPUT_OR_LABEL = 62;
final static int OBJECT = 63;
final static int FONT = 64;
final static int KEYGEN = 65;
// start insertion modes
private static final int INITIAL = 0;
private static final int BEFORE_HTML = 1;
private static final int BEFORE_HEAD = 2;
private static final int IN_HEAD = 3;
private static final int IN_HEAD_NOSCRIPT = 4;
private static final int AFTER_HEAD = 5;
private static final int IN_BODY = 6;
private static final int IN_TABLE = 7;
private static final int IN_CAPTION = 8;
private static final int IN_COLUMN_GROUP = 9;
private static final int IN_TABLE_BODY = 10;
private static final int IN_ROW = 11;
private static final int IN_CELL = 12;
private static final int IN_SELECT = 13;
private static final int IN_SELECT_IN_TABLE = 14;
private static final int AFTER_BODY = 15;
private static final int IN_FRAMESET = 16;
private static final int AFTER_FRAMESET = 17;
private static final int AFTER_AFTER_BODY = 18;
private static final int AFTER_AFTER_FRAMESET = 19;
private static final int TEXT = 20;
private static final int FRAMESET_OK = 21;
// start charset states
private static final int CHARSET_INITIAL = 0;
private static final int CHARSET_C = 1;
private static final int CHARSET_H = 2;
private static final int CHARSET_A = 3;
private static final int CHARSET_R = 4;
private static final int CHARSET_S = 5;
private static final int CHARSET_E = 6;
private static final int CHARSET_T = 7;
private static final int CHARSET_EQUALS = 8;
private static final int CHARSET_SINGLE_QUOTED = 9;
private static final int CHARSET_DOUBLE_QUOTED = 10;
private static final int CHARSET_UNQUOTED = 11;
// end pseudo enums
// [NOCPP[
private final static String[] HTML4_PUBLIC_IDS = {
"-//W3C//DTD HTML 4.0 Frameset//EN",
"-//W3C//DTD HTML 4.0 Transitional//EN",
"-//W3C//DTD HTML 4.0//EN", "-//W3C//DTD HTML 4.01 Frameset//EN",
"-//W3C//DTD HTML 4.01 Transitional//EN",
"-//W3C//DTD HTML 4.01//EN" };
// ]NOCPP]
@Literal private final static String[] QUIRKY_PUBLIC_IDS = {
"+//silmaril//dtd html pro v0r11 19970101//",
"-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
"-//as//dtd html 3.0 aswedit + extensions//",
"-//ietf//dtd html 2.0 level 1//",
"-//ietf//dtd html 2.0 level 2//",
"-//ietf//dtd html 2.0 strict level 1//",
"-//ietf//dtd html 2.0 strict level 2//",
"-//ietf//dtd html 2.0 strict//",
"-//ietf//dtd html 2.0//",
"-//ietf//dtd html 2.1e//",
"-//ietf//dtd html 3.0//",
"-//ietf//dtd html 3.2 final//",
"-//ietf//dtd html 3.2//",
"-//ietf//dtd html 3//",
"-//ietf//dtd html level 0//",
"-//ietf//dtd html level 1//",
"-//ietf//dtd html level 2//",
"-//ietf//dtd html level 3//",
"-//ietf//dtd html strict level 0//",
"-//ietf//dtd html strict level 1//",
"-//ietf//dtd html strict level 2//",
"-//ietf//dtd html strict level 3//",
"-//ietf//dtd html strict//",
"-//ietf//dtd html//",
"-//metrius//dtd metrius presentational//",
"-//microsoft//dtd internet explorer 2.0 html strict//",
"-//microsoft//dtd internet explorer 2.0 html//",
"-//microsoft//dtd internet explorer 2.0 tables//",
"-//microsoft//dtd internet explorer 3.0 html strict//",
"-//microsoft//dtd internet explorer 3.0 html//",
"-//microsoft//dtd internet explorer 3.0 tables//",
"-//netscape comm. corp.//dtd html//",
"-//netscape comm. corp.//dtd strict html//",
"-//o'reilly and associates//dtd html 2.0//",
"-//o'reilly and associates//dtd html extended 1.0//",
"-//o'reilly and associates//dtd html extended relaxed 1.0//",
"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
"-//spyglass//dtd html 2.0 extended//",
"-//sq//dtd html 2.0 hotmetal + extensions//",
"-//sun microsystems corp.//dtd hotjava html//",
"-//sun microsystems corp.//dtd hotjava strict html//",
"-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//",
"-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//",
"-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//",
"-//w3c//dtd html 4.0 transitional//",
"-//w3c//dtd html experimental 19960712//",
"-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//",
"-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//",
"-//webtechs//dtd mozilla html//" };
private static final int NOT_FOUND_ON_STACK = Integer.MAX_VALUE;
// [NOCPP[
private static final @Local String HTML_LOCAL = "html";
// ]NOCPP]
private int mode = INITIAL;
private int originalMode = INITIAL;
/**
* Used only when moving back to IN_BODY.
*/
private boolean framesetOk = true;
private boolean inForeign = false;
protected Tokenizer tokenizer;
// [NOCPP[
protected ErrorHandler errorHandler;
private DocumentModeHandler documentModeHandler;
private DoctypeExpectation doctypeExpectation = DoctypeExpectation.HTML;
// ]NOCPP]
private boolean scriptingEnabled = false;
private boolean needToDropLF;
// [NOCPP[
private boolean wantingComments;
// ]NOCPP]
private boolean fragment;
private @Local String contextName;
private @NsUri String contextNamespace;
private T contextNode;
private StackNode<T>[] stack;
private int currentPtr = -1;
private StackNode<T>[] listOfActiveFormattingElements;
private int listPtr = -1;
private T formPointer;
private T headPointer;
/**
* Used to work around Gecko limitations. Not used in Java.
*/
private T deepTreeSurrogateParent;
protected char[] charBuffer;
protected int charBufferLen = 0;
private boolean quirks = false;
// [NOCPP[
private boolean reportingDoctype = true;
private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET;
private final Map<String, LocatorImpl> idLocations = new HashMap<String, LocatorImpl>();
private boolean html4;
// ]NOCPP]
protected TreeBuilder() {
fragment = false;
}
/**
* Reports an condition that would make the infoset incompatible with XML
* 1.0 as fatal.
*
* @throws SAXException
* @throws SAXParseException
*/
protected void fatal() throws SAXException {
}
// [NOCPP[
protected final void fatal(Exception e) throws SAXException {
SAXParseException spe = new SAXParseException(e.getMessage(),
tokenizer, e);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
final void fatal(String s) throws SAXException {
SAXParseException spe = new SAXParseException(s, tokenizer);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
// ]NOCPP]
/**
* Reports a Parse Error.
*
* @param message
* the message
* @throws SAXException
*/
final void err(String message) throws SAXException {
// [NOCPP[
if (errorHandler == null) {
return;
}
errNoCheck(message);
// ]NOCPP]
}
/**
* Reports a Parse Error without checking if an error handler is present.
*
* @param message
* the message
* @throws SAXException
*/
final void errNoCheck(String message) throws SAXException {
// [NOCPP[
SAXParseException spe = new SAXParseException(message, tokenizer);
errorHandler.error(spe);
// ]NOCPP]
}
/**
* Reports a warning
*
* @param message
* the message
* @throws SAXException
*/
final void warn(String message) throws SAXException {
// [NOCPP[
if (errorHandler == null) {
return;
}
SAXParseException spe = new SAXParseException(message, tokenizer);
errorHandler.warning(spe);
// ]NOCPP]
}
@SuppressWarnings("unchecked") public final void startTokenization(Tokenizer self) throws SAXException {
tokenizer = self;
stack = new StackNode[64];
listOfActiveFormattingElements = new StackNode[64];
needToDropLF = false;
originalMode = INITIAL;
currentPtr = -1;
listPtr = -1;
Portability.releaseElement(formPointer);
formPointer = null;
Portability.releaseElement(headPointer);
headPointer = null;
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = null;
// [NOCPP[
html4 = false;
idLocations.clear();
wantingComments = wantsComments();
// ]NOCPP]
start(fragment);
charBufferLen = 0;
charBuffer = new char[1024];
framesetOk = true;
if (fragment) {
T elt;
if (contextNode != null) {
elt = contextNode;
Portability.retainElement(elt);
} else {
elt = createHtmlElementSetAsRoot(tokenizer.emptyAttributes());
}
StackNode<T> node = new StackNode<T>(
"http://www.w3.org/1999/xhtml", ElementName.HTML, elt);
currentPtr++;
stack[currentPtr] = node;
resetTheInsertionMode();
if ("title" == contextName || "textarea" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.RCDATA, contextName);
} else if ("style" == contextName || "xmp" == contextName
|| "iframe" == contextName || "noembed" == contextName
|| "noframes" == contextName
|| (scriptingEnabled && "noscript" == contextName)) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.RAWTEXT, contextName);
} else if ("plaintext" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.PLAINTEXT, contextName);
} else if ("script" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.SCRIPT_DATA,
contextName);
} else {
tokenizer.setStateAndEndTagExpectation(Tokenizer.DATA, contextName);
}
Portability.releaseLocal(contextName);
contextName = null;
Portability.releaseElement(contextNode);
contextNode = null;
Portability.releaseElement(elt);
} else {
mode = INITIAL;
inForeign = false;
}
}
public final void doctype(@Local String name, String publicIdentifier,
String systemIdentifier, boolean forceQuirks) throws SAXException {
needToDropLF = false;
if (!inForeign) {
switch (mode) {
case INITIAL:
// [NOCPP[
if (reportingDoctype) {
// ]NOCPP]
String emptyString = Portability.newEmptyString();
appendDoctypeToDocument(name == null ? "" : name,
publicIdentifier == null ? emptyString
: publicIdentifier,
systemIdentifier == null ? emptyString
: systemIdentifier);
Portability.releaseString(emptyString);
// [NOCPP[
}
switch (doctypeExpectation) {
case HTML:
// ]NOCPP]
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
false);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
err("Almost standards mode doctype. Expected \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
} else {
// [NOCPP[
if ((Portability.literalEqualsString(
"-//W3C//DTD HTML 4.0//EN",
publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString(
"http://www.w3.org/TR/REC-html40/strict.dtd",
systemIdentifier)))
|| (Portability.literalEqualsString(
"-//W3C//DTD HTML 4.01//EN",
publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString(
"http://www.w3.org/TR/html4/strict.dtd",
systemIdentifier)))
|| (Portability.literalEqualsString(
"-//W3C//DTD XHTML 1.0 Strict//EN",
publicIdentifier) && Portability.literalEqualsString(
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
systemIdentifier))
|| (Portability.literalEqualsString(
"-//W3C//DTD XHTML 1.1//EN",
publicIdentifier) && Portability.literalEqualsString(
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd",
systemIdentifier))
) {
warn("Obsolete doctype. Expected \u201C<!DOCTYPE html>\u201D.");
} else if (!((systemIdentifier == null || Portability.literalEqualsString(
"about:legacy-compat", systemIdentifier)) && publicIdentifier == null)) {
err("Legacy doctype. Expected \u201C<!DOCTYPE html>\u201D.");
}
// ]NOCPP]
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
}
// [NOCPP[
break;
case HTML401_STRICT:
html4 = true;
tokenizer.turnOnAdditionalHtml4Errors();
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
true);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
err("Almost standards mode doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
} else {
if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
} else {
err("The doctype was not the HTML 4.01 Strict doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
}
break;
case HTML401_TRANSITIONAL:
html4 = true;
tokenizer.turnOnAdditionalHtml4Errors();
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
true);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)
&& systemIdentifier != null) {
if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
} else {
err("The doctype was not a non-quirky HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
} else {
err("The doctype was not the HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
}
break;
case AUTO:
html4 = isHtml4Doctype(publicIdentifier);
if (html4) {
tokenizer.turnOnAdditionalHtml4Errors();
}
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
html4);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
} else {
err("Almost standards mode doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
}
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
html4);
} else {
if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
} else {
if (!(publicIdentifier == null && systemIdentifier == null)) {
err("Legacy doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
}
}
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
html4);
}
break;
case NO_DOCTYPE_ERRORS:
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
false);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
} else {
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
}
break;
}
// ]NOCPP]
/*
*
* Then, switch to the root element mode of the tree
* construction stage.
*/
mode = BEFORE_HTML;
return;
default:
break;
}
}
/*
* A DOCTYPE token Parse error.
*/
err("Stray doctype.");
/*
* Ignore the token.
*/
return;
}
// [NOCPP[
private boolean isHtml4Doctype(String publicIdentifier) {
if (publicIdentifier != null
&& (Arrays.binarySearch(TreeBuilder.HTML4_PUBLIC_IDS,
publicIdentifier) > -1)) {
return true;
}
return false;
}
// ]NOCPP]
public final void comment(@NoLength char[] buf, int start, int length)
throws SAXException {
needToDropLF = false;
// [NOCPP[
if (!wantingComments) {
return;
}
// ]NOCPP]
if (!inForeign) {
switch (mode) {
case INITIAL:
case BEFORE_HTML:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
/*
* A comment token Append a Comment node to the Document
* object with the data attribute set to the data given in
* the comment token.
*/
appendCommentToDocument(buf, start, length);
return;
case AFTER_BODY:
/*
* A comment token Append a Comment node to the first
* element in the stack of open elements (the html element),
* with the data attribute set to the data given in the
* comment token.
*/
flushCharacters();
appendComment(stack[0].node, buf, start, length);
return;
default:
break;
}
}
/*
* A comment token Append a Comment node to the current node with the
* data attribute set to the data given in the comment token.
*/
flushCharacters();
appendComment(stack[currentPtr].node, buf, start, length);
return;
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#characters(char[], int,
* int)
*/
public final void characters(@Const @NoLength char[] buf, int start, int length)
throws SAXException {
if (needToDropLF) {
if (buf[start] == '\n') {
start++;
length--;
if (length == 0) {
return;
}
}
needToDropLF = false;
}
if (inForeign) {
accumulateCharacters(buf, start, length);
return;
}
// optimize the most common case
switch (mode) {
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
reconstructTheActiveFormattingElements();
// fall through
case TEXT:
accumulateCharacters(buf, start, length);
return;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, start, length);
return;
default:
int end = start + length;
charactersloop: for (int i = start; i < end; i++) {
switch (buf[i]) {
case ' ':
case '\t':
case '\n':
case '\r':
case '\u000C':
/*
* A character token that is one of one of U+0009
* CHARACTER TABULATION, U+000A LINE FEED (LF),
* U+000C FORM FEED (FF), or U+0020 SPACE
*/
switch (mode) {
case INITIAL:
case BEFORE_HTML:
case BEFORE_HEAD:
/*
* Ignore the token.
*/
start = i + 1;
continue;
case IN_HEAD:
case IN_HEAD_NOSCRIPT:
case AFTER_HEAD:
case IN_COLUMN_GROUP:
case IN_FRAMESET:
case AFTER_FRAMESET:
/*
* Append the character to the current node.
*/
continue;
case FRAMESET_OK:
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
flushCharacters();
reconstructTheActiveFormattingElements();
/*
* Append the token's character to the
* current node.
*/
break charactersloop;
case IN_SELECT:
case IN_SELECT_IN_TABLE:
break charactersloop;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, i, 1);
start = i + 1;
continue;
case AFTER_BODY:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
flushCharacters();
reconstructTheActiveFormattingElements();
/*
* Append the token's character to the
* current node.
*/
continue;
}
default:
/*
* A character token that is not one of one of
* U+0009 CHARACTER TABULATION, U+000A LINE FEED
* (LF), U+000C FORM FEED (FF), or U+0020 SPACE
*/
switch (mode) {
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Non-space characters found without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(
DocumentMode.QUIRKS_MODE, null,
null, false);
/*
* Then, switch to the root element mode of
* the tree construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
i--;
continue;
case BEFORE_HTML:
/*
* Create an HTMLElement node with the tag
* name html, in the HTML namespace. Append
* it to the Document object.
*/
// No need to flush characters here,
// because there's nothing to flush.
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
i--;
continue;
case BEFORE_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* /Act as if a start tag token with the tag
* name "head" and no attributes had been
* seen,
*/
flushCharacters();
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element
* being generated, with the current token
* being reprocessed in the "after head"
* insertion mode.
*/
i--;
continue;
case IN_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if an end tag token with the tag
* name "head" had been seen,
*/
flushCharacters();
pop();
mode = AFTER_HEAD;
/*
* and reprocess the current token.
*/
i--;
continue;
case IN_HEAD_NOSCRIPT:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error. Act as if an end tag with
* the tag name "noscript" had been seen
*/
err("Non-space character inside \u201Cnoscript\u201D inside \u201Chead\u201D.");
flushCharacters();
pop();
mode = IN_HEAD;
/*
* and reprocess the current token.
*/
i--;
continue;
case AFTER_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if a start tag token with the tag
* name "body" and no attributes had been
* seen,
*/
flushCharacters();
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
/*
* and then reprocess the current token.
*/
i--;
continue;
case FRAMESET_OK:
framesetOk = false;
mode = IN_BODY;
i--;
continue;
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
flushCharacters();
reconstructTheActiveFormattingElements();
/*
* Append the token's character to the
* current node.
*/
break charactersloop;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, i, 1);
start = i + 1;
continue;
case IN_COLUMN_GROUP:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if an end tag with the tag name
* "colgroup" had been seen, and then, if
* that token wasn't ignored, reprocess the
* current token.
*/
if (currentPtr == 0) {
err("Non-space in \u201Ccolgroup\u201D when parsing fragment.");
start = i + 1;
continue;
}
flushCharacters();
pop();
mode = IN_TABLE;
i--;
continue;
case IN_SELECT:
case IN_SELECT_IN_TABLE:
break charactersloop;
case AFTER_BODY:
err("Non-space character after body.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
i--;
continue;
case IN_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error.
*/
err("Non-space in \u201Cframeset\u201D.");
/*
* Ignore the token.
*/
start = i + 1;
continue;
case AFTER_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error.
*/
err("Non-space after \u201Cframeset\u201D.");
/*
* Ignore the token.
*/
start = i + 1;
continue;
case AFTER_AFTER_BODY:
/*
* Parse error.
*/
err("Non-space character in page trailer.");
/*
* Switch back to the main mode and
* reprocess the token.
*/
mode = framesetOk ? FRAMESET_OK : IN_BODY;
i--;
continue;
case AFTER_AFTER_FRAMESET:
/*
* Parse error.
*/
err("Non-space character in page trailer.");
/*
* Switch back to the main mode and
* reprocess the token.
*/
mode = IN_FRAMESET;
i--;
continue;
}
}
}
if (start < end) {
accumulateCharacters(buf, start, end - start);
}
}
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#zeroOriginatingReplacementCharacter()
*/
@Override public void zeroOriginatingReplacementCharacter()
throws SAXException {
if (inForeign || mode == TEXT) {
characters(REPLACEMENT_CHARACTER, 0, 1);
}
}
public final void eof() throws SAXException {
flushCharacters();
eofloop: for (;;) {
if (inForeign) {
err("End of file in a foreign namespace context.");
break eofloop;
}
switch (mode) {
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("End of file seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
/*
* Create an HTMLElement node with the tag name html, in the
* HTML namespace. Append it to the Document object.
*/
appendHtmlElementToDocumentAndPush();
// XXX application cache manifest
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
case BEFORE_HEAD:
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
continue;
case IN_HEAD:
if (errorHandler != null && currentPtr > 1) {
err("End of file seen and there were open elements.");
}
while (currentPtr > 0) {
popOnEof();
}
mode = AFTER_HEAD;
continue;
case IN_HEAD_NOSCRIPT:
err("End of file seen and there were open elements.");
while (currentPtr > 1) {
popOnEof();
}
mode = IN_HEAD;
continue;
case AFTER_HEAD:
appendToCurrentNodeAndPushBodyElement();
mode = IN_BODY;
continue;
case IN_COLUMN_GROUP:
if (currentPtr == 0) {
assert fragment;
break eofloop;
} else {
popOnEof();
mode = IN_TABLE;
continue;
}
case FRAMESET_OK:
case IN_CAPTION:
case IN_CELL:
case IN_BODY:
// [NOCPP[
openelementloop: for (int i = currentPtr; i >= 0; i--) {
int group = stack[i].group;
switch (group) {
case DD_OR_DT:
case LI:
case P:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case BODY:
case HTML:
break;
default:
err("End of file seen and there were open elements.");
break openelementloop;
}
}
// ]NOCPP]
break eofloop;
case TEXT:
err("End of file seen when expecting text or an end tag.");
// XXX mark script as already executed
if (originalMode == AFTER_HEAD) {
popOnEof();
}
popOnEof();
mode = originalMode;
continue;
case IN_TABLE_BODY:
case IN_ROW:
case IN_TABLE:
case IN_SELECT:
case IN_SELECT_IN_TABLE:
case IN_FRAMESET:
if (errorHandler != null && currentPtr > 0) {
errNoCheck("End of file seen and there were open elements.");
}
break eofloop;
case AFTER_BODY:
case AFTER_FRAMESET:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
default:
// [NOCPP[
if (currentPtr == 0) { // This silliness is here to poison
// buggy compiler optimizations in
// GWT
System.currentTimeMillis();
}
// ]NOCPP]
break eofloop;
}
}
while (currentPtr > 0) {
popOnEof();
}
if (!fragment) {
popOnEof();
}
/* Stop parsing. */
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#endTokenization()
*/
public final void endTokenization() throws SAXException {
Portability.releaseElement(formPointer);
formPointer = null;
Portability.releaseElement(headPointer);
headPointer = null;
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = null;
if (stack != null) {
while (currentPtr > -1) {
stack[currentPtr].release();
currentPtr--;
}
Portability.releaseArray(stack);
stack = null;
}
if (listOfActiveFormattingElements != null) {
while (listPtr > -1) {
if (listOfActiveFormattingElements[listPtr] != null) {
listOfActiveFormattingElements[listPtr].release();
}
listPtr--;
}
Portability.releaseArray(listOfActiveFormattingElements);
listOfActiveFormattingElements = null;
}
// [NOCPP[
idLocations.clear();
// ]NOCPP]
if (charBuffer != null) {
Portability.releaseArray(charBuffer);
charBuffer = null;
}
end();
}
public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
if (mode == FRAMESET_OK) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
Portability.releaseArray(prompt);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
+ case HTML:
+ err("Stray \u201Chtml\u201D start tag.");
+ if (!fragment) {
+ addAttributesToHtml(attributes);
+ attributes = null; // CPP
+ }
+ break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
private boolean isSpecialParentInForeign(StackNode<T> stackNode) {
@NsUri String ns = stackNode.ns;
if ("http://www.w3.org/1999/xhtml" == ns) {
return true;
}
if (ns == "http://www.w3.org/2000/svg") {
return stackNode.group == FOREIGNOBJECT_OR_DESC
|| stackNode.group == TITLE;
}
assert ns == "http://www.w3.org/1998/Math/MathML" : "Unexpected namespace.";
return stackNode.group == MI_MO_MN_MS_MTEXT;
}
/**
*
* <p>
* C++ memory note: The return value must be released.
*
* @return
* @throws SAXException
* @throws StopSniffingException
*/
public static String extractCharsetFromContent(String attributeValue) {
// This is a bit ugly. Converting the string to char array in order to
// make the portability layer smaller.
int charsetState = CHARSET_INITIAL;
int start = -1;
int end = -1;
char[] buffer = Portability.newCharArrayFromString(attributeValue);
charsetloop: for (int i = 0; i < buffer.length; i++) {
char c = buffer[i];
switch (charsetState) {
case CHARSET_INITIAL:
switch (c) {
case 'c':
case 'C':
charsetState = CHARSET_C;
continue;
default:
continue;
}
case CHARSET_C:
switch (c) {
case 'h':
case 'H':
charsetState = CHARSET_H;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_H:
switch (c) {
case 'a':
case 'A':
charsetState = CHARSET_A;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_A:
switch (c) {
case 'r':
case 'R':
charsetState = CHARSET_R;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_R:
switch (c) {
case 's':
case 'S':
charsetState = CHARSET_S;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_S:
switch (c) {
case 'e':
case 'E':
charsetState = CHARSET_E;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_E:
switch (c) {
case 't':
case 'T':
charsetState = CHARSET_T;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_T:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
continue;
case '=':
charsetState = CHARSET_EQUALS;
continue;
default:
return null;
}
case CHARSET_EQUALS:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
continue;
case '\'':
start = i + 1;
charsetState = CHARSET_SINGLE_QUOTED;
continue;
case '\"':
start = i + 1;
charsetState = CHARSET_DOUBLE_QUOTED;
continue;
default:
start = i;
charsetState = CHARSET_UNQUOTED;
continue;
}
case CHARSET_SINGLE_QUOTED:
switch (c) {
case '\'':
end = i;
break charsetloop;
default:
continue;
}
case CHARSET_DOUBLE_QUOTED:
switch (c) {
case '\"':
end = i;
break charsetloop;
default:
continue;
}
case CHARSET_UNQUOTED:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
case ';':
end = i;
break charsetloop;
default:
continue;
}
}
}
String charset = null;
if (start != -1) {
if (end == -1) {
end = buffer.length;
}
charset = Portability.newStringFromBuffer(buffer, start, end
- start);
}
Portability.releaseArray(buffer);
return charset;
}
private void checkMetaCharset(HtmlAttributes attributes)
throws SAXException {
String content = attributes.getValue(AttributeName.CONTENT);
String internalCharsetLegacy = null;
if (content != null) {
internalCharsetLegacy = TreeBuilder.extractCharsetFromContent(content);
// [NOCPP[
if (errorHandler != null
&& internalCharsetLegacy != null
&& !Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"content-type",
attributes.getValue(AttributeName.HTTP_EQUIV))) {
warn("Attribute \u201Ccontent\u201D would be sniffed as an internal character encoding declaration but there was no matching \u201Chttp-equiv='Content-Type'\u201D attribute.");
}
// ]NOCPP]
}
if (internalCharsetLegacy == null) {
String internalCharsetHtml5 = attributes.getValue(AttributeName.CHARSET);
if (internalCharsetHtml5 != null) {
tokenizer.internalEncodingDeclaration(internalCharsetHtml5);
requestSuspension();
}
} else {
tokenizer.internalEncodingDeclaration(internalCharsetLegacy);
Portability.releaseString(internalCharsetLegacy);
requestSuspension();
}
}
public final void endTag(ElementName elementName) throws SAXException {
flushCharacters();
needToDropLF = false;
int eltPos;
int group = elementName.group;
@Local String name = elementName.name;
endtagloop: for (;;) {
assert !inForeign || currentPtr >= 0 : "In foreign without a root element?";
if (inForeign
&& stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
if (errorHandler != null && stack[currentPtr].name != name) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D did not match the name of the current open element (\u201C"
+ stack[currentPtr].popName + "\u201D).");
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == name) {
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
}
if (stack[--eltPos].ns == "http://www.w3.org/1999/xhtml") {
break;
}
}
}
switch (mode) {
case IN_ROW:
switch (group) {
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
break endtagloop;
case TABLE:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
case TBODY_OR_THEAD_OR_TFOOT:
if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TD_OR_TH:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_TABLE
}
case IN_TABLE_BODY:
switch (group) {
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastOrRoot(name);
if (eltPos == 0) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
break endtagloop;
case TABLE:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
assert fragment;
err("Stray end tag \u201Ctable\u201D.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
switch (group) {
case TABLE:
eltPos = findLast("table");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("Stray end tag \u201Ctable\u201D.");
break endtagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break endtagloop;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D.");
// fall through to IN_BODY
}
case IN_CAPTION:
switch (group) {
case CAPTION:
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
break endtagloop;
case TABLE:
err("\u201Ctable\u201D closed but \u201Ccaption\u201D was still open.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
case BODY:
case COL:
case COLGROUP:
case HTML:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case TD_OR_TH:
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_ROW;
break endtagloop;
case TABLE:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
closeTheCell(findLastInTableScopeTdTh());
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
case IN_BODY:
switch (group) {
case BODY:
if (!isSecondOnStackBody()) {
assert fragment;
err("Stray end tag \u201Cbody\u201D.");
break endtagloop;
}
assert currentPtr >= 1;
if (errorHandler != null) {
uncloseloop1: for (int i = 2; i <= currentPtr; i++) {
switch (stack[i].group) {
case DD_OR_DT:
case LI:
case OPTGROUP:
case OPTION: // is this possible?
case P:
case RT_OR_RP:
case TD_OR_TH:
case TBODY_OR_THEAD_OR_TFOOT:
break;
default:
err("End tag for \u201Cbody\u201D seen but there were unclosed elements.");
break uncloseloop1;
}
}
}
mode = AFTER_BODY;
break endtagloop;
case HTML:
if (!isSecondOnStackBody()) {
assert fragment;
err("Stray end tag \u201Chtml\u201D.");
break endtagloop;
}
if (errorHandler != null) {
uncloseloop2: for (int i = 0; i <= currentPtr; i++) {
switch (stack[i].group) {
case DD_OR_DT:
case LI:
case P:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case BODY:
case HTML:
break;
default:
err("End tag for \u201Chtml\u201D seen but there were unclosed elements.");
break uncloseloop2;
}
}
}
mode = AFTER_BODY;
continue;
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case PRE_OR_LISTING:
case FIELDSET:
case BUTTON:
case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case FORM:
if (formPointer == null) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
Portability.releaseElement(formPointer);
formPointer = null;
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
removeFromStack(eltPos);
break endtagloop;
case P:
eltPos = findLastInButtonScope("p");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201Cp\u201D element in scope but a \u201Cp\u201D end tag seen.");
// XXX inline this case
if (inForeign) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
pop();
}
inForeign = false;
}
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName,
HtmlAttributes.EMPTY_ATTRIBUTES);
break endtagloop;
}
generateImpliedEndTagsExceptFor("p");
assert eltPos != TreeBuilder.NOT_FOUND_ON_STACK;
if (errorHandler != null && eltPos != currentPtr) {
errNoCheck("End tag for \u201Cp\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
case LI:
eltPos = findLastInListScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201Cli\u201D element in list scope but a \u201Cli\u201D end tag seen.");
} else {
generateImpliedEndTagsExceptFor(name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("End tag for \u201Cli\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case DD_OR_DT:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201C"
+ name
+ "\u201D element in scope but a \u201C"
+ name + "\u201D end tag seen.");
} else {
generateImpliedEndTagsExceptFor(name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("End tag for \u201C"
+ name
+ "\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
eltPos = findLastInScopeHn();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case A:
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
case NOBR:
adoptionAgencyEndTag(name);
break endtagloop;
case OBJECT:
case MARQUEE_OR_APPLET:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
}
break endtagloop;
case BR:
err("End tag \u201Cbr\u201D.");
if (inForeign) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
pop();
}
inForeign = false;
}
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName,
HtmlAttributes.EMPTY_ATTRIBUTES);
break endtagloop;
case AREA_OR_WBR:
case PARAM_OR_SOURCE:
case EMBED_OR_IMG:
case IMAGE:
case INPUT:
case KEYGEN: // XXX??
case HR:
case ISINDEX:
case IFRAME:
case NOEMBED: // XXX???
case NOFRAMES: // XXX??
case SELECT:
case TABLE:
case TEXTAREA: // XXX??
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
case NOSCRIPT:
if (scriptingEnabled) {
err("Stray end tag \u201Cnoscript\u201D.");
break endtagloop;
} else {
// fall through
}
default:
if (isCurrent(name)) {
pop();
break endtagloop;
}
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos];
if (node.name == name) {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
} else if (node.scoping || node.special) {
err("Stray end tag \u201C" + name
+ "\u201D.");
break endtagloop;
}
eltPos--;
}
}
case IN_COLUMN_GROUP:
switch (group) {
case COLGROUP:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break endtagloop;
}
pop();
mode = IN_TABLE;
break endtagloop;
case COL:
err("Stray end tag \u201Ccol\u201D.");
break endtagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break endtagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TABLE:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("\u201C"
+ name
+ "\u201D end tag with \u201Cselect\u201D open.");
if (findLastInTableScope(name) != TreeBuilder.NOT_FOUND_ON_STACK) {
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break endtagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
} else {
break endtagloop;
}
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case OPTION:
if (isCurrent("option")) {
pop();
break endtagloop;
} else {
err("Stray end tag \u201Coption\u201D");
break endtagloop;
}
case OPTGROUP:
if (isCurrent("option")
&& "optgroup" == stack[currentPtr - 1].name) {
pop();
}
if (isCurrent("optgroup")) {
pop();
} else {
err("Stray end tag \u201Coptgroup\u201D");
}
break endtagloop;
case SELECT:
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("Stray end tag \u201Cselect\u201D");
break endtagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
if (fragment) {
err("Stray end tag \u201Chtml\u201D");
break endtagloop;
} else {
mode = AFTER_AFTER_BODY;
break endtagloop;
}
default:
err("Saw an end tag after \u201Cbody\u201D had been closed.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
if (currentPtr == 0) {
assert fragment;
err("Stray end tag \u201Cframeset\u201D");
break endtagloop;
}
pop();
if ((!fragment) && !isCurrent("frameset")) {
mode = AFTER_FRAMESET;
}
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
mode = AFTER_AFTER_FRAMESET;
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("End tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HEAD:
case BR:
case HTML:
case BODY:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case BEFORE_HEAD:
switch (group) {
case HEAD:
case BR:
case HTML:
case BODY:
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case IN_HEAD:
switch (group) {
case HEAD:
pop();
mode = AFTER_HEAD;
break endtagloop;
case BR:
case HTML:
case BODY:
pop();
mode = AFTER_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case NOSCRIPT:
pop();
mode = IN_HEAD;
break endtagloop;
case BR:
err("Stray end tag \u201C" + name + "\u201D.");
pop();
mode = IN_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case AFTER_HEAD:
switch (group) {
case HTML:
case BODY:
case BR:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case AFTER_AFTER_BODY:
err("Stray \u201C" + name + "\u201D end tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
case AFTER_AFTER_FRAMESET:
err("Stray \u201C" + name + "\u201D end tag.");
mode = IN_FRAMESET;
continue;
case TEXT:
// XXX need to manage insertion point here
pop();
if (originalMode == AFTER_HEAD) {
silentPop();
}
mode = originalMode;
break endtagloop;
}
} // endtagloop
if (inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
}
private int findLastInTableScopeOrRootTbodyTheadTfoot() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == TreeBuilder.TBODY_OR_THEAD_OR_TFOOT) {
return i;
}
}
return 0;
}
private int findLast(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInTableScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].name == "table") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInButtonScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping || stack[i].name == "button") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping) {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInListScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping || stack[i].name == "ul" || stack[i].name == "ol") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInScopeHn() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == TreeBuilder.H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
return i;
} else if (stack[i].scoping) {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private boolean hasForeignInScope() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].ns != "http://www.w3.org/1999/xhtml") {
return true;
} else if (stack[i].scoping) {
return false;
}
}
return false;
}
private void generateImpliedEndTagsExceptFor(@Local String name)
throws SAXException {
for (;;) {
StackNode<T> node = stack[currentPtr];
switch (node.group) {
case P:
case LI:
case DD_OR_DT:
case OPTION:
case OPTGROUP:
case RT_OR_RP:
if (node.name == name) {
return;
}
pop();
continue;
default:
return;
}
}
}
private void generateImpliedEndTags() throws SAXException {
for (;;) {
switch (stack[currentPtr].group) {
case P:
case LI:
case DD_OR_DT:
case OPTION:
case OPTGROUP:
case RT_OR_RP:
pop();
continue;
default:
return;
}
}
}
private boolean isSecondOnStackBody() {
return currentPtr >= 1 && stack[1].group == TreeBuilder.BODY;
}
private void documentModeInternal(DocumentMode m, String publicIdentifier,
String systemIdentifier, boolean html4SpecificAdditionalErrorChecks)
throws SAXException {
quirks = (m == DocumentMode.QUIRKS_MODE);
if (documentModeHandler != null) {
documentModeHandler.documentMode(
m
// [NOCPP[
, publicIdentifier, systemIdentifier,
html4SpecificAdditionalErrorChecks
// ]NOCPP]
);
}
// [NOCPP[
documentMode(m, publicIdentifier, systemIdentifier,
html4SpecificAdditionalErrorChecks);
// ]NOCPP]
}
private boolean isAlmostStandards(String publicIdentifier,
String systemIdentifier) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd xhtml 1.0 transitional//en", publicIdentifier)) {
return true;
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd xhtml 1.0 frameset//en", publicIdentifier)) {
return true;
}
if (systemIdentifier != null) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) {
return true;
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) {
return true;
}
}
return false;
}
private boolean isQuirky(@Local String name, String publicIdentifier,
String systemIdentifier, boolean forceQuirks) {
if (forceQuirks) {
return true;
}
if (name != HTML_LOCAL) {
return true;
}
if (publicIdentifier != null) {
for (int i = 0; i < TreeBuilder.QUIRKY_PUBLIC_IDS.length; i++) {
if (Portability.lowerCaseLiteralIsPrefixOfIgnoreAsciiCaseString(
TreeBuilder.QUIRKY_PUBLIC_IDS[i], publicIdentifier)) {
return true;
}
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3o//dtd w3 html strict 3.0//en//", publicIdentifier)
|| Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-/w3c/dtd html 4.0 transitional/en",
publicIdentifier)
|| Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"html", publicIdentifier)) {
return true;
}
}
if (systemIdentifier == null) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) {
return true;
} else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) {
return true;
}
} else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",
systemIdentifier)) {
return true;
}
return false;
}
private void closeTheCell(int eltPos) throws SAXException {
generateImpliedEndTags();
if (errorHandler != null && eltPos != currentPtr) {
errNoCheck("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_ROW;
return;
}
private int findLastInTableScopeTdTh() {
for (int i = currentPtr; i > 0; i--) {
@Local String name = stack[i].name;
if ("td" == name || "th" == name) {
return i;
} else if (name == "table") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private void clearStackBackTo(int eltPos) throws SAXException {
while (currentPtr > eltPos) { // > not >= intentional
pop();
}
}
private void resetTheInsertionMode() {
inForeign = false;
StackNode<T> node;
@Local String name;
@NsUri String ns;
for (int i = currentPtr; i >= 0; i--) {
node = stack[i];
name = node.name;
ns = node.ns;
if (i == 0) {
if (!(contextNamespace == "http://www.w3.org/1999/xhtml" && (contextName == "td" || contextName == "th"))) {
name = contextName;
ns = contextNamespace;
} else {
mode = framesetOk ? FRAMESET_OK : IN_BODY; // XXX from Hixie's email
return;
}
}
if ("select" == name) {
mode = IN_SELECT;
return;
} else if ("td" == name || "th" == name) {
mode = IN_CELL;
return;
} else if ("tr" == name) {
mode = IN_ROW;
return;
} else if ("tbody" == name || "thead" == name || "tfoot" == name) {
mode = IN_TABLE_BODY;
return;
} else if ("caption" == name) {
mode = IN_CAPTION;
return;
} else if ("colgroup" == name) {
mode = IN_COLUMN_GROUP;
return;
} else if ("table" == name) {
mode = IN_TABLE;
return;
} else if ("http://www.w3.org/1999/xhtml" != ns) {
inForeign = true;
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
} else if ("head" == name) {
mode = framesetOk ? FRAMESET_OK : IN_BODY; // really
return;
} else if ("body" == name) {
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
} else if ("frameset" == name) {
mode = IN_FRAMESET;
return;
} else if ("html" == name) {
if (headPointer == null) {
mode = BEFORE_HEAD;
} else {
mode = AFTER_HEAD;
}
return;
} else if (i == 0) {
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
}
}
}
/**
* @throws SAXException
*
*/
private void implicitlyCloseP() throws SAXException {
int eltPos = findLastInButtonScope("p");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
return;
}
generateImpliedEndTagsExceptFor("p");
if (errorHandler != null && eltPos != currentPtr) {
err("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
private boolean clearLastStackSlot() {
stack[currentPtr] = null;
return true;
}
private boolean clearLastListSlot() {
listOfActiveFormattingElements[listPtr] = null;
return true;
}
@SuppressWarnings("unchecked") private void push(StackNode<T> node) throws SAXException {
currentPtr++;
if (currentPtr == stack.length) {
StackNode<T>[] newStack = new StackNode[stack.length + 64];
System.arraycopy(stack, 0, newStack, 0, stack.length);
Portability.releaseArray(stack);
stack = newStack;
}
stack[currentPtr] = node;
elementPushed(node.ns, node.popName, node.node);
}
@SuppressWarnings("unchecked") private void silentPush(StackNode<T> node) throws SAXException {
currentPtr++;
if (currentPtr == stack.length) {
StackNode<T>[] newStack = new StackNode[stack.length + 64];
System.arraycopy(stack, 0, newStack, 0, stack.length);
Portability.releaseArray(stack);
stack = newStack;
}
stack[currentPtr] = node;
}
@SuppressWarnings("unchecked") private void append(StackNode<T> node) {
listPtr++;
if (listPtr == listOfActiveFormattingElements.length) {
StackNode<T>[] newList = new StackNode[listOfActiveFormattingElements.length + 64];
System.arraycopy(listOfActiveFormattingElements, 0, newList, 0,
listOfActiveFormattingElements.length);
Portability.releaseArray(listOfActiveFormattingElements);
listOfActiveFormattingElements = newList;
}
listOfActiveFormattingElements[listPtr] = node;
}
@Inline private void insertMarker() {
append(null);
}
private void clearTheListOfActiveFormattingElementsUpToTheLastMarker() {
while (listPtr > -1) {
if (listOfActiveFormattingElements[listPtr] == null) {
--listPtr;
return;
}
listOfActiveFormattingElements[listPtr].release();
--listPtr;
}
}
@Inline private boolean isCurrent(@Local String name) {
return name == stack[currentPtr].name;
}
private void removeFromStack(int pos) throws SAXException {
if (currentPtr == pos) {
pop();
} else {
fatal();
stack[pos].release();
System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos);
assert clearLastStackSlot();
currentPtr--;
}
}
private void removeFromStack(StackNode<T> node) throws SAXException {
if (stack[currentPtr] == node) {
pop();
} else {
int pos = currentPtr - 1;
while (pos >= 0 && stack[pos] != node) {
pos--;
}
if (pos == -1) {
// dead code?
return;
}
fatal();
node.release();
System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos);
currentPtr--;
}
}
private void removeFromListOfActiveFormattingElements(int pos) {
assert listOfActiveFormattingElements[pos] != null;
listOfActiveFormattingElements[pos].release();
if (pos == listPtr) {
assert clearLastListSlot();
listPtr--;
return;
}
assert pos < listPtr;
System.arraycopy(listOfActiveFormattingElements, pos + 1,
listOfActiveFormattingElements, pos, listPtr - pos);
assert clearLastListSlot();
listPtr--;
}
private void adoptionAgencyEndTag(@Local String name) throws SAXException {
// If you crash around here, perhaps some stack node variable claimed to
// be a weak ref isn't.
for (;;) {
int formattingEltListPos = listPtr;
while (formattingEltListPos > -1) {
StackNode<T> listNode = listOfActiveFormattingElements[formattingEltListPos]; // weak
// ref
if (listNode == null) {
formattingEltListPos = -1;
break;
} else if (listNode.name == name) {
break;
}
formattingEltListPos--;
}
if (formattingEltListPos == -1) {
err("No element \u201C" + name + "\u201D to close.");
return;
}
StackNode<T> formattingElt = listOfActiveFormattingElements[formattingEltListPos]; // this
// *looks*
// like
// a
// weak
// ref
// to
// the
// list
// of
// formatting
// elements
int formattingEltStackPos = currentPtr;
boolean inScope = true;
while (formattingEltStackPos > -1) {
StackNode<T> node = stack[formattingEltStackPos]; // weak ref
if (node == formattingElt) {
break;
} else if (node.scoping) {
inScope = false;
}
formattingEltStackPos--;
}
if (formattingEltStackPos == -1) {
err("No element \u201C" + name + "\u201D to close.");
removeFromListOfActiveFormattingElements(formattingEltListPos);
return;
}
if (!inScope) {
err("No element \u201C" + name + "\u201D to close.");
return;
}
// stackPos now points to the formatting element and it is in scope
if (errorHandler != null && formattingEltStackPos != currentPtr) {
errNoCheck("End tag \u201C" + name + "\u201D violates nesting rules.");
}
int furthestBlockPos = formattingEltStackPos + 1;
while (furthestBlockPos <= currentPtr) {
StackNode<T> node = stack[furthestBlockPos]; // weak ref
if (node.scoping || node.special) {
break;
}
furthestBlockPos++;
}
if (furthestBlockPos > currentPtr) {
// no furthest block
while (currentPtr >= formattingEltStackPos) {
pop();
}
removeFromListOfActiveFormattingElements(formattingEltListPos);
return;
}
StackNode<T> commonAncestor = stack[formattingEltStackPos - 1]; // weak
// ref
StackNode<T> furthestBlock = stack[furthestBlockPos]; // weak ref
// detachFromParent(furthestBlock.node); XXX AAA CHANGE
int bookmark = formattingEltListPos;
int nodePos = furthestBlockPos;
StackNode<T> lastNode = furthestBlock; // weak ref
for (;;) {
nodePos--;
StackNode<T> node = stack[nodePos]; // weak ref
int nodeListPos = findInListOfActiveFormattingElements(node);
if (nodeListPos == -1) {
assert formattingEltStackPos < nodePos;
assert bookmark < nodePos;
assert furthestBlockPos > nodePos;
removeFromStack(nodePos); // node is now a bad pointer in
// C++
furthestBlockPos--;
continue;
}
// now node is both on stack and in the list
if (nodePos == formattingEltStackPos) {
break;
}
if (nodePos == furthestBlockPos) {
bookmark = nodeListPos + 1;
}
// if (hasChildren(node.node)) { XXX AAA CHANGE
assert node == listOfActiveFormattingElements[nodeListPos];
assert node == stack[nodePos];
T clone = createElement("http://www.w3.org/1999/xhtml",
node.name, node.attributes.cloneAttributes(null));
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, clone, node.scoping, node.special,
node.fosterParenting, node.popName, node.attributes); // creation
// ownership
// goes
// to
// stack
node.dropAttributes(); // adopt ownership to newNode
stack[nodePos] = newNode;
newNode.retain(); // retain for list
listOfActiveFormattingElements[nodeListPos] = newNode;
node.release(); // release from stack
node.release(); // release from list
node = newNode;
Portability.releaseElement(clone);
// } XXX AAA CHANGE
detachFromParent(lastNode.node);
appendElement(lastNode.node, node.node);
lastNode = node;
}
if (commonAncestor.fosterParenting) {
fatal();
detachFromParent(lastNode.node);
insertIntoFosterParent(lastNode.node);
} else {
detachFromParent(lastNode.node);
appendElement(lastNode.node, commonAncestor.node);
}
T clone = createElement("http://www.w3.org/1999/xhtml",
formattingElt.name,
formattingElt.attributes.cloneAttributes(null));
StackNode<T> formattingClone = new StackNode<T>(
formattingElt.group, formattingElt.ns, formattingElt.name,
clone, formattingElt.scoping, formattingElt.special,
formattingElt.fosterParenting, formattingElt.popName,
formattingElt.attributes); // Ownership
// transfers
// to
// stack
// below
formattingElt.dropAttributes(); // transfer ownership to
// formattingClone
appendChildrenToNewParent(furthestBlock.node, clone);
appendElement(clone, furthestBlock.node);
removeFromListOfActiveFormattingElements(formattingEltListPos);
insertIntoListOfActiveFormattingElements(formattingClone, bookmark);
assert formattingEltStackPos < furthestBlockPos;
removeFromStack(formattingEltStackPos);
// furthestBlockPos is now off by one and points to the slot after
// it
insertIntoStack(formattingClone, furthestBlockPos);
Portability.releaseElement(clone);
}
}
private void insertIntoStack(StackNode<T> node, int position)
throws SAXException {
assert currentPtr + 1 < stack.length;
assert position <= currentPtr + 1;
if (position == currentPtr + 1) {
push(node);
} else {
System.arraycopy(stack, position, stack, position + 1,
(currentPtr - position) + 1);
currentPtr++;
stack[position] = node;
}
}
private void insertIntoListOfActiveFormattingElements(
StackNode<T> formattingClone, int bookmark) {
formattingClone.retain();
assert listPtr + 1 < listOfActiveFormattingElements.length;
if (bookmark <= listPtr) {
System.arraycopy(listOfActiveFormattingElements, bookmark,
listOfActiveFormattingElements, bookmark + 1,
(listPtr - bookmark) + 1);
}
listPtr++;
listOfActiveFormattingElements[bookmark] = formattingClone;
}
private int findInListOfActiveFormattingElements(StackNode<T> node) {
for (int i = listPtr; i >= 0; i--) {
if (node == listOfActiveFormattingElements[i]) {
return i;
}
}
return -1;
}
private int findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker(
@Local String name) {
for (int i = listPtr; i >= 0; i--) {
StackNode<T> node = listOfActiveFormattingElements[i];
if (node == null) {
return -1;
} else if (node.name == name) {
return i;
}
}
return -1;
}
private int findLastOrRoot(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
}
}
return 0;
}
private int findLastOrRoot(int group) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == group) {
return i;
}
}
return 0;
}
/**
* Attempt to add attribute to the body element.
* @param attributes the attributes
* @return <code>true</code> iff the attributes were added
* @throws SAXException
*/
private boolean addAttributesToBody(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
if (currentPtr >= 1) {
StackNode<T> body = stack[1];
if (body.group == TreeBuilder.BODY) {
addAttributesToElement(body.node, attributes);
return true;
}
}
return false;
}
private void addAttributesToHtml(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
addAttributesToElement(stack[0].node, attributes);
}
private void pushHeadPointerOntoStack() throws SAXException {
assert headPointer != null;
assert !fragment;
assert mode == AFTER_HEAD;
fatal();
silentPush(new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD,
headPointer));
}
/**
* @throws SAXException
*
*/
private void reconstructTheActiveFormattingElements() throws SAXException {
if (listPtr == -1) {
return;
}
StackNode<T> mostRecent = listOfActiveFormattingElements[listPtr];
if (mostRecent == null || isInStack(mostRecent)) {
return;
}
int entryPos = listPtr;
for (;;) {
entryPos--;
if (entryPos == -1) {
break;
}
if (listOfActiveFormattingElements[entryPos] == null) {
break;
}
if (isInStack(listOfActiveFormattingElements[entryPos])) {
break;
}
}
while (entryPos < listPtr) {
entryPos++;
StackNode<T> entry = listOfActiveFormattingElements[entryPos];
T clone = createElement("http://www.w3.org/1999/xhtml", entry.name,
entry.attributes.cloneAttributes(null));
StackNode<T> entryClone = new StackNode<T>(entry.group, entry.ns,
entry.name, clone, entry.scoping, entry.special,
entry.fosterParenting, entry.popName, entry.attributes);
entry.dropAttributes(); // transfer ownership to entryClone
StackNode<T> currentNode = stack[currentPtr];
if (currentNode.fosterParenting) {
insertIntoFosterParent(clone);
} else {
appendElement(clone, currentNode.node);
}
push(entryClone);
// stack takes ownership of the local variable
listOfActiveFormattingElements[entryPos] = entryClone;
// overwriting the old entry on the list, so release & retain
entry.release();
entryClone.retain();
}
}
private void insertIntoFosterParent(T child) throws SAXException {
int eltPos = findLastOrRoot(TreeBuilder.TABLE);
StackNode<T> node = stack[eltPos];
T elt = node.node;
if (eltPos == 0) {
appendElement(child, elt);
return;
}
insertFosterParentedChild(child, elt, stack[eltPos - 1].node);
}
private boolean isInStack(StackNode<T> node) {
for (int i = currentPtr; i >= 0; i--) {
if (stack[i] == node) {
return true;
}
}
return false;
}
private void pop() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
elementPopped(node.ns, node.popName, node.node);
node.release();
}
private void silentPop() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
node.release();
}
private void popOnEof() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
markMalformedIfScript(node.node);
elementPopped(node.ns, node.popName, node.node);
node.release();
}
// [NOCPP[
private void checkAttributes(HtmlAttributes attributes, @NsUri String ns)
throws SAXException {
if (errorHandler != null) {
int len = attributes.getXmlnsLength();
for (int i = 0; i < len; i++) {
AttributeName name = attributes.getXmlnsAttributeName(i);
if (name == AttributeName.XMLNS) {
if (html4) {
err("Attribute \u201Cxmlns\u201D not allowed here. (HTML4-only error.)");
} else {
String xmlns = attributes.getXmlnsValue(i);
if (!ns.equals(xmlns)) {
err("Bad value \u201C"
+ xmlns
+ "\u201D for the attribute \u201Cxmlns\u201D (only \u201C"
+ ns + "\u201D permitted here).");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0.");
break;
case FATAL:
fatal("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0.");
break;
}
}
}
} else if (ns != "http://www.w3.org/1999/xhtml"
&& name == AttributeName.XMLNS_XLINK) {
String xmlns = attributes.getXmlnsValue(i);
if (!"http://www.w3.org/1999/xlink".equals(xmlns)) {
err("Bad value \u201C"
+ xmlns
+ "\u201D for the attribute \u201Cxmlns:link\u201D (only \u201Chttp://www.w3.org/1999/xlink\u201D permitted here).");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics.");
break;
case FATAL:
fatal("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics.");
break;
}
}
} else {
err("Attribute \u201C" + attributes.getXmlnsLocalName(i)
+ "\u201D not allowed here.");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute with the local name \u201C"
+ attributes.getXmlnsLocalName(i)
+ "\u201D is not serializable as XML 1.0.");
break;
case FATAL:
fatal("Attribute with the local name \u201C"
+ attributes.getXmlnsLocalName(i)
+ "\u201D is not serializable as XML 1.0.");
break;
}
}
}
}
attributes.processNonNcNames(this, namePolicy);
}
private String checkPopName(@Local String name) throws SAXException {
if (NCName.isNCName(name)) {
return name;
} else {
switch (namePolicy) {
case ALLOW:
warn("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
return name;
case ALTER_INFOSET:
warn("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
return NCName.escapeName(name);
case FATAL:
fatal("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
}
}
return null; // keep compiler happy
}
// ]NOCPP]
private void appendHtmlElementToDocumentAndPush(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createHtmlElementSetAsRoot(attributes);
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.HTML, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendHtmlElementToDocumentAndPush() throws SAXException {
appendHtmlElementToDocumentAndPush(tokenizer.emptyAttributes());
}
private void appendToCurrentNodeAndPushHeadElement(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "head",
attributes);
appendElement(elt, stack[currentPtr].node);
headPointer = elt;
Portability.retainElement(headPointer);
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.HEAD, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushBodyElement(HtmlAttributes attributes)
throws SAXException {
appendToCurrentNodeAndPushElement("http://www.w3.org/1999/xhtml",
ElementName.BODY, attributes);
}
private void appendToCurrentNodeAndPushBodyElement() throws SAXException {
appendToCurrentNodeAndPushBodyElement(tokenizer.emptyAttributes());
}
private void appendToCurrentNodeAndPushFormElementMayFoster(
HtmlAttributes attributes) throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "form",
attributes);
formPointer = elt;
Portability.retainElement(formPointer);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.FORM, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushFormattingElementMayFoster(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// This method can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt,
attributes.cloneAttributes(null));
push(node);
append(node);
node.retain(); // append doesn't retain itself
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElement(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// This method can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes);
appendElement(elt, stack[currentPtr].node);
StackNode<T> node = new StackNode<T>(ns, elementName, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFosterNoScoping(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName,
false);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFosterCamelCase(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.camelCaseName;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName,
ElementName.FOREIGNOBJECT == elementName);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes, T form)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes, fragment ? null
: form);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFoster(
@NsUri String ns, @Local String name, HtmlAttributes attributes,
T form) throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, name, attributes, fragment ? null : form);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, name, elt);
elementPopped(ns, name, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFoster(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, popName, elt);
elementPopped(ns, popName, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFosterCamelCase(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.camelCaseName;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, popName, elt);
elementPopped(ns, popName, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrent(
@NsUri String ns, @Local String name, HtmlAttributes attributes,
T form) throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, name, attributes, fragment ? null : form);
StackNode<T> current = stack[currentPtr];
appendElement(elt, current.node);
elementPushed(ns, name, elt);
elementPopped(ns, name, elt);
Portability.releaseElement(elt);
}
private void appendVoidFormToCurrent(HtmlAttributes attributes) throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "form",
attributes);
formPointer = elt;
// ownership transferred to form pointer
StackNode<T> current = stack[currentPtr];
appendElement(elt, current.node);
elementPushed("http://www.w3.org/1999/xhtml", "form", elt);
elementPopped("http://www.w3.org/1999/xhtml", "form", elt);
}
// [NOCPP[
private final void accumulateCharactersForced(@Const @NoLength char[] buf,
int start, int length) throws SAXException {
int newLen = charBufferLen + length;
if (newLen > charBuffer.length) {
char[] newBuf = new char[newLen];
System.arraycopy(charBuffer, 0, newBuf, 0, charBufferLen);
Portability.releaseArray(charBuffer);
charBuffer = newBuf;
}
System.arraycopy(buf, start, charBuffer, charBufferLen, length);
charBufferLen = newLen;
}
// ]NOCPP]
protected void accumulateCharacters(@Const @NoLength char[] buf, int start,
int length) throws SAXException {
appendCharacters(stack[currentPtr].node, buf, start, length);
}
// ------------------------------- //
protected final void requestSuspension() {
tokenizer.requestSuspension();
}
protected abstract T createElement(@NsUri String ns, @Local String name,
HtmlAttributes attributes) throws SAXException;
protected T createElement(@NsUri String ns, @Local String name,
HtmlAttributes attributes, T form) throws SAXException {
return createElement("http://www.w3.org/1999/xhtml", name, attributes);
}
protected abstract T createHtmlElementSetAsRoot(HtmlAttributes attributes)
throws SAXException;
protected abstract void detachFromParent(T element) throws SAXException;
protected abstract boolean hasChildren(T element) throws SAXException;
protected abstract void appendElement(T child, T newParent)
throws SAXException;
protected abstract void appendChildrenToNewParent(T oldParent, T newParent)
throws SAXException;
protected abstract void insertFosterParentedChild(T child, T table,
T stackParent) throws SAXException;
protected abstract void insertFosterParentedCharacters(
@NoLength char[] buf, int start, int length, T table, T stackParent)
throws SAXException;
protected abstract void appendCharacters(T parent, @NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void appendIsindexPrompt(T parent) throws SAXException;
protected abstract void appendComment(T parent, @NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void appendCommentToDocument(@NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void addAttributesToElement(T element,
HtmlAttributes attributes) throws SAXException;
protected void markMalformedIfScript(T elt) throws SAXException {
}
protected void start(boolean fragmentMode) throws SAXException {
}
protected void end() throws SAXException {
}
protected void appendDoctypeToDocument(@Local String name,
String publicIdentifier, String systemIdentifier)
throws SAXException {
}
protected void elementPushed(@NsUri String ns, @Local String name, T node)
throws SAXException {
}
protected void elementPopped(@NsUri String ns, @Local String name, T node)
throws SAXException {
}
// [NOCPP[
protected void documentMode(DocumentMode m, String publicIdentifier,
String systemIdentifier, boolean html4SpecificAdditionalErrorChecks)
throws SAXException {
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#wantsComments()
*/
public boolean wantsComments() {
return wantingComments;
}
public void setIgnoringComments(boolean ignoreComments) {
wantingComments = !ignoreComments;
}
/**
* Sets the errorHandler.
*
* @param errorHandler
* the errorHandler to set
*/
public final void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Returns the errorHandler.
*
* @return the errorHandler
*/
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* The argument MUST be an interned string or <code>null</code>.
*
* @param context
*/
public final void setFragmentContext(@Local String context) {
this.contextName = context;
this.contextNamespace = "http://www.w3.org/1999/xhtml";
this.contextNode = null;
this.fragment = (contextName != null);
this.quirks = false;
}
// ]NOCPP]
/**
* The argument MUST be an interned string or <code>null</code>.
*
* @param context
*/
public final void setFragmentContext(@Local String context,
@NsUri String ns, T node, boolean quirks) {
this.contextName = context;
Portability.retainLocal(context);
this.contextNamespace = ns;
this.contextNode = node;
Portability.retainElement(node);
this.fragment = (contextName != null);
this.quirks = quirks;
}
protected final T currentNode() {
return stack[currentPtr].node;
}
/**
* Returns the scriptingEnabled.
*
* @return the scriptingEnabled
*/
public boolean isScriptingEnabled() {
return scriptingEnabled;
}
/**
* Sets the scriptingEnabled.
*
* @param scriptingEnabled
* the scriptingEnabled to set
*/
public void setScriptingEnabled(boolean scriptingEnabled) {
this.scriptingEnabled = scriptingEnabled;
}
// [NOCPP[
/**
* Sets the doctypeExpectation.
*
* @param doctypeExpectation
* the doctypeExpectation to set
*/
public void setDoctypeExpectation(DoctypeExpectation doctypeExpectation) {
this.doctypeExpectation = doctypeExpectation;
}
public void setNamePolicy(XmlViolationPolicy namePolicy) {
this.namePolicy = namePolicy;
}
/**
* Sets the documentModeHandler.
*
* @param documentModeHandler
* the documentModeHandler to set
*/
public void setDocumentModeHandler(DocumentModeHandler documentModeHandler) {
this.documentModeHandler = documentModeHandler;
}
/**
* Sets the reportingDoctype.
*
* @param reportingDoctype
* the reportingDoctype to set
*/
public void setReportingDoctype(boolean reportingDoctype) {
this.reportingDoctype = reportingDoctype;
}
// ]NOCPP]
/**
* Flushes the pending characters. Public for document.write use cases only.
* @throws SAXException
*/
public final void flushCharacters() throws SAXException {
if (charBufferLen > 0) {
if ((mode == IN_TABLE || mode == IN_TABLE_BODY || mode == IN_ROW)
&& charBufferContainsNonWhitespace()) {
err("Misplaced non-space characters insided a table.");
reconstructTheActiveFormattingElements();
if (!stack[currentPtr].fosterParenting) {
// reconstructing gave us a new current node
appendCharacters(currentNode(), charBuffer, 0,
charBufferLen);
charBufferLen = 0;
return;
}
int eltPos = findLastOrRoot(TreeBuilder.TABLE);
StackNode<T> node = stack[eltPos];
T elt = node.node;
if (eltPos == 0) {
appendCharacters(elt, charBuffer, 0, charBufferLen);
charBufferLen = 0;
return;
}
insertFosterParentedCharacters(charBuffer, 0, charBufferLen,
elt, stack[eltPos - 1].node);
charBufferLen = 0;
return;
}
appendCharacters(currentNode(), charBuffer, 0, charBufferLen);
charBufferLen = 0;
}
}
private boolean charBufferContainsNonWhitespace() {
for (int i = 0; i < charBufferLen; i++) {
switch (charBuffer[i]) {
case ' ':
case '\t':
case '\n':
case '\r':
case '\u000C':
continue;
default:
return true;
}
}
return false;
}
/**
* Creates a comparable snapshot of the tree builder state. Snapshot
* creation is only supported immediately after a script end tag has been
* processed. In C++ the caller is responsible for calling
* <code>delete</code> on the returned object.
*
* @return a snapshot.
* @throws SAXException
*/
@SuppressWarnings("unchecked") public TreeBuilderState<T> newSnapshot()
throws SAXException {
StackNode<T>[] listCopy = new StackNode[listPtr + 1];
for (int i = 0; i < listCopy.length; i++) {
StackNode<T> node = listOfActiveFormattingElements[i];
if (node != null) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, node.node, node.scoping, node.special,
node.fosterParenting, node.popName,
node.attributes.cloneAttributes(null));
listCopy[i] = newNode;
} else {
listCopy[i] = null;
}
}
StackNode<T>[] stackCopy = new StackNode[currentPtr + 1];
for (int i = 0; i < stackCopy.length; i++) {
StackNode<T> node = stack[i];
int listIndex = findInListOfActiveFormattingElements(node);
if (listIndex == -1) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, node.node, node.scoping, node.special,
node.fosterParenting, node.popName,
null);
stackCopy[i] = newNode;
} else {
stackCopy[i] = listCopy[listIndex];
stackCopy[i].retain();
}
}
Portability.retainElement(formPointer);
return new StateSnapshot<T>(stackCopy, listCopy, formPointer, headPointer, deepTreeSurrogateParent, mode, originalMode, framesetOk, inForeign, needToDropLF, quirks);
}
public boolean snapshotMatches(TreeBuilderState<T> snapshot) {
StackNode<T>[] stackCopy = snapshot.getStack();
int stackLen = snapshot.getStackLength();
StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements();
int listLen = snapshot.getListOfActiveFormattingElementsLength();
if (stackLen != currentPtr + 1
|| listLen != listPtr + 1
|| formPointer != snapshot.getFormPointer()
|| headPointer != snapshot.getHeadPointer()
|| deepTreeSurrogateParent != snapshot.getDeepTreeSurrogateParent()
|| mode != snapshot.getMode()
|| originalMode != snapshot.getOriginalMode()
|| framesetOk != snapshot.isFramesetOk()
|| inForeign != snapshot.isInForeign()
|| needToDropLF != snapshot.isNeedToDropLF()
|| quirks != snapshot.isQuirks()) { // maybe just assert quirks
return false;
}
for (int i = listLen - 1; i >= 0; i--) {
if (listCopy[i] == null
&& listOfActiveFormattingElements[i] == null) {
continue;
} else if (listCopy[i] == null
|| listOfActiveFormattingElements[i] == null) {
return false;
}
if (listCopy[i].node != listOfActiveFormattingElements[i].node) {
return false; // it's possible that this condition is overly
// strict
}
}
for (int i = stackLen - 1; i >= 0; i--) {
if (stackCopy[i].node != stack[i].node) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked") public void loadState(
TreeBuilderState<T> snapshot, Interner interner)
throws SAXException {
StackNode<T>[] stackCopy = snapshot.getStack();
int stackLen = snapshot.getStackLength();
StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements();
int listLen = snapshot.getListOfActiveFormattingElementsLength();
for (int i = 0; i <= listPtr; i++) {
if (listOfActiveFormattingElements[i] != null) {
listOfActiveFormattingElements[i].release();
}
}
if (listOfActiveFormattingElements.length < listLen) {
Portability.releaseArray(listOfActiveFormattingElements);
listOfActiveFormattingElements = new StackNode[listLen];
}
listPtr = listLen - 1;
for (int i = 0; i <= currentPtr; i++) {
stack[i].release();
}
if (stack.length < stackLen) {
Portability.releaseArray(stack);
stack = new StackNode[stackLen];
}
currentPtr = stackLen - 1;
for (int i = 0; i < listLen; i++) {
StackNode<T> node = listCopy[i];
if (node != null) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
Portability.newLocalFromLocal(node.name, interner), node.node,
node.scoping, node.special, node.fosterParenting,
Portability.newLocalFromLocal(node.popName, interner),
node.attributes.cloneAttributes(null));
listOfActiveFormattingElements[i] = newNode;
} else {
listOfActiveFormattingElements[i] = null;
}
}
for (int i = 0; i < stackLen; i++) {
StackNode<T> node = stackCopy[i];
int listIndex = findInArray(node, listCopy);
if (listIndex == -1) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
Portability.newLocalFromLocal(node.name, interner), node.node,
node.scoping, node.special, node.fosterParenting,
Portability.newLocalFromLocal(node.popName, interner),
null);
stack[i] = newNode;
} else {
stack[i] = listOfActiveFormattingElements[listIndex];
stack[i].retain();
}
}
Portability.releaseElement(formPointer);
formPointer = snapshot.getFormPointer();
Portability.retainElement(formPointer);
Portability.releaseElement(headPointer);
headPointer = snapshot.getHeadPointer();
Portability.retainElement(headPointer);
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = snapshot.getDeepTreeSurrogateParent();
Portability.retainElement(deepTreeSurrogateParent);
mode = snapshot.getMode();
originalMode = snapshot.getOriginalMode();
framesetOk = snapshot.isFramesetOk();
inForeign = snapshot.isInForeign();
needToDropLF = snapshot.isNeedToDropLF();
quirks = snapshot.isQuirks();
}
private int findInArray(StackNode<T> node, StackNode<T>[] arr) {
for (int i = listPtr; i >= 0; i--) {
if (node == arr[i]) {
return i;
}
}
return -1;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getFormPointer()
*/
public T getFormPointer() {
return formPointer;
}
/**
* Returns the headPointer.
*
* @return the headPointer
*/
public T getHeadPointer() {
return headPointer;
}
/**
* Returns the deepTreeSurrogateParent.
*
* @return the deepTreeSurrogateParent
*/
public T getDeepTreeSurrogateParent() {
return deepTreeSurrogateParent;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElements()
*/
public StackNode<T>[] getListOfActiveFormattingElements() {
return listOfActiveFormattingElements;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getStack()
*/
public StackNode<T>[] getStack() {
return stack;
}
/**
* Returns the mode.
*
* @return the mode
*/
public int getMode() {
return mode;
}
/**
* Returns the originalMode.
*
* @return the originalMode
*/
public int getOriginalMode() {
return originalMode;
}
/**
* Returns the framesetOk.
*
* @return the framesetOk
*/
public boolean isFramesetOk() {
return framesetOk;
}
/**
* Returns the foreignFlag.
*
* @see nu.validator.htmlparser.common.TokenHandler#isInForeign()
* @return the foreignFlag
*/
public boolean isInForeign() {
return inForeign;
}
/**
* Returns the needToDropLF.
*
* @return the needToDropLF
*/
public boolean isNeedToDropLF() {
return needToDropLF;
}
/**
* Returns the quirks.
*
* @return the quirks
*/
public boolean isQuirks() {
return quirks;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElementsLength()
*/
public int getListOfActiveFormattingElementsLength() {
return listPtr + 1;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getStackLength()
*/
public int getStackLength() {
return currentPtr + 1;
}
}
| true | true | public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
if (mode == FRAMESET_OK) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
Portability.releaseArray(prompt);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
| public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
if (mode == FRAMESET_OK) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_DIR_OR_ARTICLE_OR_ASIDE_OR_DATAGRID_OR_DETAILS_OR_HGROUP_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_NAV_OR_SECTION:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
Portability.releaseArray(prompt);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
|
diff --git a/src/main/java/com/feedme/activity/AddChildActivity.java b/src/main/java/com/feedme/activity/AddChildActivity.java
index 6f95dc4..cb6ee1b 100644
--- a/src/main/java/com/feedme/activity/AddChildActivity.java
+++ b/src/main/java/com/feedme/activity/AddChildActivity.java
@@ -1,256 +1,256 @@
package com.feedme.activity;
import android.app.*;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.feedme.R;
import com.feedme.dao.BabyDao;
import com.feedme.model.Baby;
import java.util.Calendar;
import java.util.List;
/**
* User: dayel.ostraco
* Date: 1/16/12
* Time: 12:27 PM
*/
public class AddChildActivity extends ChildActivity
{
private Button babyDob;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_child);
googleAnalyticsTracker.startNewSession(TRACKING_ID, this);
googleAnalyticsTracker.trackPageView("/Add-Child");
final BabyDao babyDao = new BabyDao(getApplicationContext());
final Baby baby = (Baby) getIntent().getSerializableExtra("baby");
// button listener for add child button
final EditText babyName = (EditText) findViewById(R.id.babyName);
final Spinner babySex = (Spinner) findViewById(R.id.babySex);
final EditText babyHeight = (EditText) findViewById(R.id.babyHeight);
final EditText babyWeight = (EditText) findViewById(R.id.babyWeight);
final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture);
if (baby != null)
{
if (baby.getPicturePath() != null && !baby.getPicturePath().equals(""))
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 12;
Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options);
babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90));
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
} else {
babyImage.setImageResource(R.drawable.babyicon);
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
}
}
Button addChildButton = (Button) findViewById(R.id.addChildButton);
Button takePicture = (Button) findViewById(R.id.takePicture);
Button selectPicture = (Button) findViewById(R.id.pickPicture);
babyDob = (Button) findViewById(R.id.babyDob);
// add a click listener to the button
babyDob.setOnClickListener(showDateDialog());
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDateDisplay();
//populate male/female spinner
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.babySex, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.babySex);
s.setAdapter(adapter);
//In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add
// Child screen.
if (getIntent().getStringExtra("picturePath") != null)
{
baby.setPicturePath(getIntent().getStringExtra("picturePath"));
babyName.setText(baby.getName());
babyHeight.setText(baby.getHeight());
babyWeight.setText(baby.getWeight());
babyDob.setText(baby.getDob());
//Set Spinner Value for Baby Sex
if (baby.getDob().equals("Male"))
{
babySex.setSelection(0);
}
else
{
babySex.setSelection(1);
}
}
//Take Picture Button
- takePicture.setOnClickListener(takePictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID));
+ takePicture.setOnClickListener(takePictureListener(0, ADD_CHILD_ACTIVITY_ID));
//Select Picture Button
- selectPicture.setOnClickListener(selectPictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID));
+ selectPicture.setOnClickListener(selectPictureListener(0, ADD_CHILD_ACTIVITY_ID));
//declare alert dialog
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
//Add Child Button
addChildButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//if name, weight, and height aren't filled out, throw an alert
if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") ||
babyWeight.getText().toString().equals("")) {
alertDialog.setTitle("Oops!");
alertDialog.setMessage("Please fill out the form completely.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
alertDialog.show();
}
else
{
Baby addBaby = new Baby(babyName.getText().toString(),
babySex.getSelectedItem().toString(),
babyHeight.getText().toString(),
babyWeight.getText().toString(),
babyDob.getText().toString(),
baby.getPicturePath());
// Inserting baby
Log.d("Insert: ", "Inserting ..");
babyDao.addBaby(addBaby);
Log.d("BABY:ADD: ", addBaby.dump());
// Reading all babies
Log.d("Reading: ", "Reading all babies..");
List<Baby> babies = babyDao.getAllBabies();
for (Baby baby : babies) {
String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex()
+ " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," +
"DOB: " + baby.getDob();
// Writing babies to log
Log.d("Name: ", log);
}
babyName.setText("");
babyHeight.setText("");
babyWeight.setText("");
babyDob.setText("");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID);
}
}
});
}
@Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.home:
startActivity(new Intent(AddChildActivity.this,
HomeActivity.class));
break;
case R.id.settings:
startActivity(new Intent(AddChildActivity.this,
SettingsActivity.class));
break;
case R.id.report:
startActivity(new Intent(AddChildActivity.this,
ReportBugActivity.class));
break;
}
return true;
}
// updates the date we display in the TextView
private void updateDateDisplay()
{
babyDob.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDateDisplay();
}
};
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_child);
googleAnalyticsTracker.startNewSession(TRACKING_ID, this);
googleAnalyticsTracker.trackPageView("/Add-Child");
final BabyDao babyDao = new BabyDao(getApplicationContext());
final Baby baby = (Baby) getIntent().getSerializableExtra("baby");
// button listener for add child button
final EditText babyName = (EditText) findViewById(R.id.babyName);
final Spinner babySex = (Spinner) findViewById(R.id.babySex);
final EditText babyHeight = (EditText) findViewById(R.id.babyHeight);
final EditText babyWeight = (EditText) findViewById(R.id.babyWeight);
final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture);
if (baby != null)
{
if (baby.getPicturePath() != null && !baby.getPicturePath().equals(""))
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 12;
Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options);
babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90));
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
} else {
babyImage.setImageResource(R.drawable.babyicon);
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
}
}
Button addChildButton = (Button) findViewById(R.id.addChildButton);
Button takePicture = (Button) findViewById(R.id.takePicture);
Button selectPicture = (Button) findViewById(R.id.pickPicture);
babyDob = (Button) findViewById(R.id.babyDob);
// add a click listener to the button
babyDob.setOnClickListener(showDateDialog());
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDateDisplay();
//populate male/female spinner
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.babySex, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.babySex);
s.setAdapter(adapter);
//In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add
// Child screen.
if (getIntent().getStringExtra("picturePath") != null)
{
baby.setPicturePath(getIntent().getStringExtra("picturePath"));
babyName.setText(baby.getName());
babyHeight.setText(baby.getHeight());
babyWeight.setText(baby.getWeight());
babyDob.setText(baby.getDob());
//Set Spinner Value for Baby Sex
if (baby.getDob().equals("Male"))
{
babySex.setSelection(0);
}
else
{
babySex.setSelection(1);
}
}
//Take Picture Button
takePicture.setOnClickListener(takePictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID));
//Select Picture Button
selectPicture.setOnClickListener(selectPictureListener(baby.getId(), ADD_CHILD_ACTIVITY_ID));
//declare alert dialog
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
//Add Child Button
addChildButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//if name, weight, and height aren't filled out, throw an alert
if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") ||
babyWeight.getText().toString().equals("")) {
alertDialog.setTitle("Oops!");
alertDialog.setMessage("Please fill out the form completely.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
alertDialog.show();
}
else
{
Baby addBaby = new Baby(babyName.getText().toString(),
babySex.getSelectedItem().toString(),
babyHeight.getText().toString(),
babyWeight.getText().toString(),
babyDob.getText().toString(),
baby.getPicturePath());
// Inserting baby
Log.d("Insert: ", "Inserting ..");
babyDao.addBaby(addBaby);
Log.d("BABY:ADD: ", addBaby.dump());
// Reading all babies
Log.d("Reading: ", "Reading all babies..");
List<Baby> babies = babyDao.getAllBabies();
for (Baby baby : babies) {
String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex()
+ " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," +
"DOB: " + baby.getDob();
// Writing babies to log
Log.d("Name: ", log);
}
babyName.setText("");
babyHeight.setText("");
babyWeight.setText("");
babyDob.setText("");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID);
}
}
});
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_child);
googleAnalyticsTracker.startNewSession(TRACKING_ID, this);
googleAnalyticsTracker.trackPageView("/Add-Child");
final BabyDao babyDao = new BabyDao(getApplicationContext());
final Baby baby = (Baby) getIntent().getSerializableExtra("baby");
// button listener for add child button
final EditText babyName = (EditText) findViewById(R.id.babyName);
final Spinner babySex = (Spinner) findViewById(R.id.babySex);
final EditText babyHeight = (EditText) findViewById(R.id.babyHeight);
final EditText babyWeight = (EditText) findViewById(R.id.babyWeight);
final ImageView babyImage = (ImageView) findViewById(R.id.babyPicture);
if (baby != null)
{
if (baby.getPicturePath() != null && !baby.getPicturePath().equals(""))
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 12;
Bitmap bmImg = BitmapFactory.decodeFile(baby.getPicturePath(), options);
babyImage.setImageBitmap(getResizedBitmap(bmImg, 75, 75, 90));
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
} else {
babyImage.setImageResource(R.drawable.babyicon);
babyImage.setMaxWidth(100);
babyImage.setMaxHeight(100);
babyImage.setMinimumWidth(100);
babyImage.setMinimumHeight(100);
}
}
Button addChildButton = (Button) findViewById(R.id.addChildButton);
Button takePicture = (Button) findViewById(R.id.takePicture);
Button selectPicture = (Button) findViewById(R.id.pickPicture);
babyDob = (Button) findViewById(R.id.babyDob);
// add a click listener to the button
babyDob.setOnClickListener(showDateDialog());
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDateDisplay();
//populate male/female spinner
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.babySex, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.babySex);
s.setAdapter(adapter);
//In the even that the user clicked Take Picture or Select Picture and fired off a new Intent from the Add
// Child screen.
if (getIntent().getStringExtra("picturePath") != null)
{
baby.setPicturePath(getIntent().getStringExtra("picturePath"));
babyName.setText(baby.getName());
babyHeight.setText(baby.getHeight());
babyWeight.setText(baby.getWeight());
babyDob.setText(baby.getDob());
//Set Spinner Value for Baby Sex
if (baby.getDob().equals("Male"))
{
babySex.setSelection(0);
}
else
{
babySex.setSelection(1);
}
}
//Take Picture Button
takePicture.setOnClickListener(takePictureListener(0, ADD_CHILD_ACTIVITY_ID));
//Select Picture Button
selectPicture.setOnClickListener(selectPictureListener(0, ADD_CHILD_ACTIVITY_ID));
//declare alert dialog
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
//Add Child Button
addChildButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//if name, weight, and height aren't filled out, throw an alert
if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") ||
babyWeight.getText().toString().equals("")) {
alertDialog.setTitle("Oops!");
alertDialog.setMessage("Please fill out the form completely.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
alertDialog.show();
}
else
{
Baby addBaby = new Baby(babyName.getText().toString(),
babySex.getSelectedItem().toString(),
babyHeight.getText().toString(),
babyWeight.getText().toString(),
babyDob.getText().toString(),
baby.getPicturePath());
// Inserting baby
Log.d("Insert: ", "Inserting ..");
babyDao.addBaby(addBaby);
Log.d("BABY:ADD: ", addBaby.dump());
// Reading all babies
Log.d("Reading: ", "Reading all babies..");
List<Baby> babies = babyDao.getAllBabies();
for (Baby baby : babies) {
String log = "Id: " + baby.getId() + " ,Name: " + baby.getName() + " ,Sex: " + baby.getSex()
+ " ,Height: " + baby.getHeight() + " ,Weight: " + baby.getWeight() + " ," +
"DOB: " + baby.getDob();
// Writing babies to log
Log.d("Name: ", log);
}
babyName.setText("");
babyHeight.setText("");
babyWeight.setText("");
babyDob.setText("");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivityForResult(intent, ADD_CHILD_ACTIVITY_ID);
}
}
});
}
|
diff --git a/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java b/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java
index 798db4d11..f69f6791d 100644
--- a/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java
+++ b/restconfig/src/main/java/org/geoserver/catalog/rest/FeatureTypeListResource.java
@@ -1,38 +1,38 @@
/* Copyright (c) 2001 - 2009 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.catalog.rest;
import java.util.List;
import org.geoserver.catalog.Catalog;
import org.geoserver.catalog.DataStoreInfo;
import org.geoserver.catalog.FeatureTypeInfo;
import org.geoserver.catalog.NamespaceInfo;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
public class FeatureTypeListResource extends AbstractCatalogListResource {
public FeatureTypeListResource(Context context, Request request,
Response response, Catalog catalog) {
super(context, request, response, FeatureTypeInfo.class, catalog);
}
@Override
protected List handleListGet() throws Exception {
String ws = getAttribute( "workspace" );
String ds = getAttribute("datastore");
if ( ds != null ) {
- DataStoreInfo dataStore = catalog.getDataStoreByName( ds );
+ DataStoreInfo dataStore = catalog.getDataStoreByName(ws, ds);
return catalog.getFeatureTypesByDataStore(dataStore);
}
NamespaceInfo ns = catalog.getNamespaceByPrefix( ws );
return catalog.getFeatureTypesByNamespace( ns );
}
}
| true | true | protected List handleListGet() throws Exception {
String ws = getAttribute( "workspace" );
String ds = getAttribute("datastore");
if ( ds != null ) {
DataStoreInfo dataStore = catalog.getDataStoreByName( ds );
return catalog.getFeatureTypesByDataStore(dataStore);
}
NamespaceInfo ns = catalog.getNamespaceByPrefix( ws );
return catalog.getFeatureTypesByNamespace( ns );
}
| protected List handleListGet() throws Exception {
String ws = getAttribute( "workspace" );
String ds = getAttribute("datastore");
if ( ds != null ) {
DataStoreInfo dataStore = catalog.getDataStoreByName(ws, ds);
return catalog.getFeatureTypesByDataStore(dataStore);
}
NamespaceInfo ns = catalog.getNamespaceByPrefix( ws );
return catalog.getFeatureTypesByNamespace( ns );
}
|
diff --git a/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java b/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java
index 25e9d5068..6b83e821f 100644
--- a/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java
+++ b/dbflute/src/main/java/org/seasar/dbflute/logic/dumpdata/DfDumpDataExtractor.java
@@ -1,104 +1,117 @@
package org.seasar.dbflute.logic.dumpdata;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.dbflute.properties.DfAbstractHelperProperties;
/**
* @author jflute
* @since 0.8.3 (2008/10/28 Tuesday)
*/
public class DfDumpDataExtractor {
// ===============================================================================
// Definition
// ==========
/** Log-instance */
private static final Log _log = LogFactory.getLog(DfAbstractHelperProperties.class);
// ===================================================================================
// Attribute
// =========
protected DataSource _dataSource;
// ===================================================================================
// Constructor
// ===========
public DfDumpDataExtractor(DataSource dataSource) {
_dataSource = dataSource;
}
// ===================================================================================
// Extract
// =======
/**
* Extract data.
* @param tableColumnMap The map of table and column. (NotNull)
* @param limit The limit of records. (If it's minus value, extracts all records.)
*/
public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) {
final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>();
+ Connection conn = null;
try {
+ conn = _dataSource.getConnection();
final Set<String> tableNameSet = tableColumnMap.keySet();
for (String tableName : tableNameSet) {
final List<String> columnNameList = tableColumnMap.get(tableName);
- final Connection conn = _dataSource.getConnection();
- final Statement statement = conn.createStatement();
final String selectClause = buildSelectClause(columnNameList);
final String fromClause = buildFromClause(tableName);
final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>();
+ Statement statement = null;
try {
+ statement = conn.createStatement();
final String sql = selectClause + " " + fromClause;
final ResultSet rs = statement.executeQuery(sql);
int count = 0;
while (rs.next()) {
if (limit >= 0 && limit <= count) {
break;
}
final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>();
for (String columnName : columnNameList) {
final String columnValue = rs.getString(columnName);
recordMap.put(columnName, columnValue);
}
recordList.add(recordMap);
++count;
}
_log.info(" " + tableName + "(" + recordList.size() + ")");
} catch (SQLException ignored) {
_log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage());
+ } finally {
+ if (statement != null) {
+ statement.close();
+ }
}
dumpDataMap.put(tableName, recordList);
}
} catch (SQLException e) {
throw new IllegalStateException(e);
+ } finally {
+ if (conn != null) {
+ try {
+ conn.close();
+ } catch (SQLException ignored) {
+ }
+ }
}
return dumpDataMap;
}
protected String buildSelectClause(List<String> columnNameList) {
final StringBuilder sb = new StringBuilder();
for (String columnName : columnNameList) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(columnName);
}
return sb.insert(0, "select ").toString();
}
protected String buildFromClause(String tableName) {
return "from " + tableName;
}
}
| false | true | public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) {
final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>();
try {
final Set<String> tableNameSet = tableColumnMap.keySet();
for (String tableName : tableNameSet) {
final List<String> columnNameList = tableColumnMap.get(tableName);
final Connection conn = _dataSource.getConnection();
final Statement statement = conn.createStatement();
final String selectClause = buildSelectClause(columnNameList);
final String fromClause = buildFromClause(tableName);
final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>();
try {
final String sql = selectClause + " " + fromClause;
final ResultSet rs = statement.executeQuery(sql);
int count = 0;
while (rs.next()) {
if (limit >= 0 && limit <= count) {
break;
}
final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>();
for (String columnName : columnNameList) {
final String columnValue = rs.getString(columnName);
recordMap.put(columnName, columnValue);
}
recordList.add(recordMap);
++count;
}
_log.info(" " + tableName + "(" + recordList.size() + ")");
} catch (SQLException ignored) {
_log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage());
}
dumpDataMap.put(tableName, recordList);
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
return dumpDataMap;
}
| public Map<String, List<Map<String, String>>> extractData(Map<String, List<String>> tableColumnMap, int limit) {
final Map<String, List<Map<String, String>>> dumpDataMap = new LinkedHashMap<String, List<Map<String, String>>>();
Connection conn = null;
try {
conn = _dataSource.getConnection();
final Set<String> tableNameSet = tableColumnMap.keySet();
for (String tableName : tableNameSet) {
final List<String> columnNameList = tableColumnMap.get(tableName);
final String selectClause = buildSelectClause(columnNameList);
final String fromClause = buildFromClause(tableName);
final List<Map<String, String>> recordList = new ArrayList<Map<String, String>>();
Statement statement = null;
try {
statement = conn.createStatement();
final String sql = selectClause + " " + fromClause;
final ResultSet rs = statement.executeQuery(sql);
int count = 0;
while (rs.next()) {
if (limit >= 0 && limit <= count) {
break;
}
final LinkedHashMap<String, String> recordMap = new LinkedHashMap<String, String>();
for (String columnName : columnNameList) {
final String columnValue = rs.getString(columnName);
recordMap.put(columnName, columnValue);
}
recordList.add(recordMap);
++count;
}
_log.info(" " + tableName + "(" + recordList.size() + ")");
} catch (SQLException ignored) {
_log.info("Failed to extract data of " + tableName + ": " + ignored.getMessage());
} finally {
if (statement != null) {
statement.close();
}
}
dumpDataMap.put(tableName, recordList);
}
} catch (SQLException e) {
throw new IllegalStateException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ignored) {
}
}
}
return dumpDataMap;
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java
index eb999da99..d5c1a44d0 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java
@@ -1,576 +1,575 @@
/*******************************************************************************
* Copyright (c) 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.team.internal.ui.history;
import java.util.ArrayList;
import java.util.HashMap;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.*;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IOpenEventListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamStatus;
import org.eclipse.team.core.history.IFileHistory;
import org.eclipse.team.core.history.IFileRevision;
import org.eclipse.team.internal.core.history.LocalFileHistory;
import org.eclipse.team.internal.core.history.LocalFileRevision;
import org.eclipse.team.internal.ui.*;
import org.eclipse.team.internal.ui.actions.CompareRevisionAction;
import org.eclipse.team.internal.ui.actions.OpenRevisionAction;
import org.eclipse.team.ui.history.HistoryPage;
import org.eclipse.team.ui.history.IHistoryPageSite;
import org.eclipse.ui.*;
import org.eclipse.ui.progress.IProgressConstants;
import com.ibm.icu.util.Calendar;
public class LocalHistoryPage extends HistoryPage {
/* private */ IFile file;
/* private */ IFileRevision currentFileRevision;
// cached for efficiency
/* private */ LocalFileHistory localFileHistory;
/* private */IFileRevision[] entries;
/* private */ TreeViewer treeViewer;
/* private */boolean shutdown = false;
//grouping on
private boolean groupingOn;
//toggle constants for default click action
private boolean compareMode = false;
protected LocalHistoryTableProvider historyTableProvider;
private RefreshFileHistory refreshFileHistoryJob;
private Composite localComposite;
private Action groupByDateMode;
private Action collapseAll;
private Action compareModeAction;
private CompareRevisionAction compareAction;
private OpenRevisionAction openAction;
private HistoryResourceListener resourceListener;
public boolean inputSet() {
currentFileRevision = null;
IFile tempFile = getFile();
this.file = tempFile;
if (tempFile == null)
return false;
//blank current input only after we're sure that we have a file
//to fetch history for
this.treeViewer.setInput(null);
localFileHistory = new LocalFileHistory(file);
if (refreshFileHistoryJob == null)
refreshFileHistoryJob = new RefreshFileHistory();
//always refresh the history if the input gets set
refreshHistory(true);
return true;
}
private IFile getFile() {
Object obj = getInput();
if (obj instanceof IFile)
return (IFile) obj;
return null;
}
private void refreshHistory(boolean refetch) {
if (refreshFileHistoryJob.getState() != Job.NONE){
refreshFileHistoryJob.cancel();
}
refreshFileHistoryJob.setFileHistory(localFileHistory);
refreshFileHistoryJob.setGrouping(groupingOn);
IHistoryPageSite parentSite = getHistoryPageSite();
Utils.schedule(refreshFileHistoryJob, getWorkbenchSite(parentSite));
}
private IWorkbenchPartSite getWorkbenchSite(IHistoryPageSite parentSite) {
IWorkbenchPart part = parentSite.getPart();
if (part != null)
return part.getSite();
return null;
}
public void createControl(Composite parent) {
localComposite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
localComposite.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
data.grabExcessVerticalSpace = true;
localComposite.setLayoutData(data);
treeViewer = createTree(localComposite);
contributeActions();
IHistoryPageSite parentSite = getHistoryPageSite();
if (parentSite != null && parentSite instanceof DialogHistoryPageSite && treeViewer != null)
parentSite.setSelectionProvider(treeViewer);
resourceListener = new HistoryResourceListener();
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
}
private void contributeActions() {
final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore();
//Group by Date
groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){
public void run() {
groupingOn = !groupingOn;
- compareModeAction.setChecked(groupingOn);
store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn);
refreshHistory(false);
}
};
groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE);
groupByDateMode.setChecked(groupingOn);
groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip);
groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
//Collapse All
collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) {
public void run() {
treeViewer.collapseAll();
}
};
collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip);
collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
//Compare Mode Action
compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) {
public void run() {
compareMode = !compareMode;
compareModeAction.setChecked(compareMode);
}
};
compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip);
compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setChecked(false);
// Click Compare action
compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
compareAction.setCurrentFileRevision(getCurrentFileRevision());
compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
compareAction.setPage(this);
openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
openAction.setPage(this);
OpenStrategy handler = new OpenStrategy(treeViewer.getTree());
handler.addOpenListener(new IOpenEventListener() {
public void handleOpen(SelectionEvent e) {
StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection();
if (compareMode){
StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()});
compareAction.selectionChanged(sel);
compareAction.run();
} else {
//Pass in the entire structured selection to allow for multiple editor openings
StructuredSelection sel = tableStructuredSelection;
openAction.selectionChanged(sel);
openAction.run();
}
}
});
//Contribute actions to popup menu
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(treeViewer.getTree());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
treeViewer.getTree().setMenu(menu);
//Don't add the object contribution menu items if this page is hosted in a dialog
IHistoryPageSite parentSite = getHistoryPageSite();
/*if (!parentSite.isModal()) {
IWorkbenchPart part = parentSite.getPart();
if (part != null) {
IWorkbenchPartSite workbenchPartSite = part.getSite();
workbenchPartSite.registerContextMenu(menuMgr, treeViewer);
}
IPageSite pageSite = parentSite.getWorkbenchPageSite();
if (pageSite != null) {
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
if (actionBarsMenu != null){
actionBarsMenu.add(toggleTextWrapAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleTextAction);
actionBarsMenu.add(toggleListAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(cvsHistoryFilter);
actionBarsMenu.add(toggleFilterAction);
}
actionBars.updateActionBars();
}
}*/
//Create the local tool bar
IToolBarManager tbm = parentSite.getToolBarManager();
if (tbm != null) {
//Add groups
tbm.add(new Separator("grouping")); //$NON-NLS-1$
tbm.appendToGroup("grouping", groupByDateMode); //$NON-NLS-1$
tbm.add(new Separator("modes")); //$NON-NLS-1$
tbm.add(new Separator("collapse")); //$NON-NLS-1$
tbm.appendToGroup("collapse", collapseAll); //$NON-NLS-1$
tbm.appendToGroup("collapse", compareModeAction); //$NON-NLS-1$
tbm.update(false);
}
}
protected void fillTableMenu(IMenuManager manager) {
// file actions go first (view file)
IHistoryPageSite parentSite = getHistoryPageSite();
manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE));
if (file != null && !parentSite.isModal()){
manager.add(openAction);
manager.add(compareAction);
}
}
/**
* Creates the tree that displays the local file revisions
*
* @param the parent composite to contain the group
* @return the group control
*/
protected TreeViewer createTree(Composite parent) {
historyTableProvider = new LocalHistoryTableProvider();
TreeViewer viewer = historyTableProvider.createTree(parent);
viewer.setContentProvider(new ITreeContentProvider() {
public Object[] getElements(Object inputElement) {
// The entries of already been fetch so return them
if (entries != null)
return entries;
if (!(inputElement instanceof IFileHistory) &&
!(inputElement instanceof AbstractHistoryCategory[]))
return new Object[0];
if (inputElement instanceof AbstractHistoryCategory[]){
return (AbstractHistoryCategory[]) inputElement;
}
final IFileHistory fileHistory = (IFileHistory) inputElement;
entries = fileHistory.getFileRevisions();
return entries;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
entries = null;
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof AbstractHistoryCategory){
return ((AbstractHistoryCategory) parentElement).getRevisions();
}
return null;
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
if (element instanceof AbstractHistoryCategory){
return ((AbstractHistoryCategory) element).hasRevisions();
}
return false;
}
});
return viewer;
}
public Control getControl() {
return localComposite;
}
public void setFocus() {
localComposite.setFocus();
}
public String getDescription() {
if (file != null)
return file.getFullPath().toString();
return null;
}
public String getName() {
if (file != null)
return file.getName();
return ""; //$NON-NLS-1$
}
public boolean isValidInput(Object object) {
//true if object is an unshared file
if (object instanceof IFile) {
if (!RepositoryProvider.isShared(((IFile) object).getProject()))
return true;
}
return false;
}
public void refresh() {
refreshHistory(true);
}
public Object getAdapter(Class adapter) {
// TODO Auto-generated method stub
return null;
}
public void dispose() {
shutdown = true;
if (resourceListener != null){
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
resourceListener = null;
}
//Cancel any incoming
if (refreshFileHistoryJob != null) {
if (refreshFileHistoryJob.getState() != Job.NONE) {
refreshFileHistoryJob.cancel();
}
}
}
public IFileRevision getCurrentFileRevision() {
if (currentFileRevision != null)
return currentFileRevision;
if (file != null)
currentFileRevision = new LocalFileRevision(file);
return currentFileRevision;
}
private class RefreshFileHistory extends Job {
private final static int NUMBER_OF_CATEGORIES = 4;
private LocalFileHistory fileHistory;
private AbstractHistoryCategory[] categories;
private boolean grouping;
private Object[] elementsToExpand;
public RefreshFileHistory() {
super(TeamUIMessages.LocalHistoryPage_FetchLocalHistoryMessage);
}
public void setFileHistory(LocalFileHistory fileHistory) {
this.fileHistory = fileHistory;
}
public void setGrouping (boolean value){
this.grouping = value;
}
public IStatus run(IProgressMonitor monitor) {
IStatus status = Status.OK_STATUS;
if (fileHistory != null && !shutdown) {
//If fileHistory termintates in a bad way, try to fetch the local
//revisions only
try {
fileHistory.refresh(monitor);
} catch (CoreException ex) {
status = new TeamStatus(ex.getStatus().getSeverity(), TeamUIPlugin.ID, ex.getStatus().getCode(), ex.getMessage(), ex, file);
}
if (grouping)
sortRevisions();
Utils.asyncExec(new Runnable() {
public void run() {
historyTableProvider.setFile(file);
if (grouping) {
mapExpandedElements(treeViewer.getExpandedElements());
treeViewer.getTree().setRedraw(false);
treeViewer.setInput(categories);
//if user is switching modes and already has expanded elements
//selected try to expand those, else expand all
if (elementsToExpand.length > 0)
treeViewer.setExpandedElements(elementsToExpand);
else {
treeViewer.expandAll();
Object[] el = treeViewer.getExpandedElements();
if (el != null && el.length > 0) {
treeViewer.setSelection(new StructuredSelection(el[0]));
treeViewer.getTree().deselectAll();
}
}
treeViewer.getTree().setRedraw(true);
} else {
if (fileHistory.getFileRevisions().length > 0) {
treeViewer.setInput(fileHistory);
} else {
categories = new AbstractHistoryCategory[] {getErrorMessage()};
treeViewer.setInput(categories);
}
}
}
}, treeViewer);
}
if (status != Status.OK_STATUS ) {
this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE);
}
return status;
}
private void mapExpandedElements(Object[] expandedElements) {
//store the names of the currently expanded categories in a map
HashMap elementMap = new HashMap();
for (int i=0; i<expandedElements.length; i++){
elementMap.put(((DateHistoryCategory)expandedElements[i]).getName(), null);
}
//Go through the new categories and keep track of the previously expanded ones
ArrayList expandable = new ArrayList();
for (int i = 0; i<categories.length; i++){
//check to see if this category is currently expanded
if (elementMap.containsKey(categories[i].getName())){
expandable.add(categories[i]);
}
}
elementsToExpand = new Object[expandable.size()];
elementsToExpand = (Object[]) expandable.toArray(new Object[expandable.size()]);
}
private boolean sortRevisions() {
IFileRevision[] fileRevision = fileHistory.getFileRevisions();
//Create the 4 categories
DateHistoryCategory[] tempCategories = new DateHistoryCategory[NUMBER_OF_CATEGORIES];
//Get a calendar instance initialized to the current time
Calendar currentCal = Calendar.getInstance();
tempCategories[0] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Today, currentCal, null);
//Get yesterday
Calendar yesterdayCal = Calendar.getInstance();
yesterdayCal.roll(Calendar.DAY_OF_YEAR, -1);
tempCategories[1] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Yesterday, yesterdayCal, null);
//Get this month
Calendar monthCal = Calendar.getInstance();
monthCal.set(Calendar.DAY_OF_MONTH, 1);
tempCategories[2] = new DateHistoryCategory(TeamUIMessages.HistoryPage_ThisMonth, monthCal, yesterdayCal);
//Everything before after week is previous
tempCategories[3] = new DateHistoryCategory(TeamUIMessages.HistoryPage_Previous, null, monthCal);
ArrayList finalCategories = new ArrayList();
for (int i = 0; i<NUMBER_OF_CATEGORIES; i++){
tempCategories[i].collectFileRevisions(fileRevision, false);
if (tempCategories[i].hasRevisions())
finalCategories.add(tempCategories[i]);
}
//Assume that some revisions have been found
boolean revisionsFound = true;
if (finalCategories.size() == 0){
//no revisions found for the current mode, so add a message category
finalCategories.add(getErrorMessage());
revisionsFound = false;
}
categories = (AbstractHistoryCategory[])finalCategories.toArray(new AbstractHistoryCategory[finalCategories.size()]);
return revisionsFound;
}
private MessageHistoryCategory getErrorMessage(){
MessageHistoryCategory messageCategory = new MessageHistoryCategory(TeamUIMessages.LocalHistoryPage_NoRevisionsFound);
return messageCategory;
}
}
private class HistoryResourceListener implements IResourceChangeListener {
/**
* @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
*/
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta root = event.getDelta();
if (file == null)
return;
IResourceDelta resourceDelta = root.findMember(file.getFullPath());
if (resourceDelta != null){
Display.getDefault().asyncExec(new Runnable() {
public void run() {
refresh();
}
});
}
}
}
}
| true | true | private void contributeActions() {
final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore();
//Group by Date
groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){
public void run() {
groupingOn = !groupingOn;
compareModeAction.setChecked(groupingOn);
store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn);
refreshHistory(false);
}
};
groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE);
groupByDateMode.setChecked(groupingOn);
groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip);
groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
//Collapse All
collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) {
public void run() {
treeViewer.collapseAll();
}
};
collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip);
collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
//Compare Mode Action
compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) {
public void run() {
compareMode = !compareMode;
compareModeAction.setChecked(compareMode);
}
};
compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip);
compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setChecked(false);
// Click Compare action
compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
compareAction.setCurrentFileRevision(getCurrentFileRevision());
compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
compareAction.setPage(this);
openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
openAction.setPage(this);
OpenStrategy handler = new OpenStrategy(treeViewer.getTree());
handler.addOpenListener(new IOpenEventListener() {
public void handleOpen(SelectionEvent e) {
StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection();
if (compareMode){
StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()});
compareAction.selectionChanged(sel);
compareAction.run();
} else {
//Pass in the entire structured selection to allow for multiple editor openings
StructuredSelection sel = tableStructuredSelection;
openAction.selectionChanged(sel);
openAction.run();
}
}
});
//Contribute actions to popup menu
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(treeViewer.getTree());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
treeViewer.getTree().setMenu(menu);
//Don't add the object contribution menu items if this page is hosted in a dialog
IHistoryPageSite parentSite = getHistoryPageSite();
/*if (!parentSite.isModal()) {
IWorkbenchPart part = parentSite.getPart();
if (part != null) {
IWorkbenchPartSite workbenchPartSite = part.getSite();
workbenchPartSite.registerContextMenu(menuMgr, treeViewer);
}
IPageSite pageSite = parentSite.getWorkbenchPageSite();
if (pageSite != null) {
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
if (actionBarsMenu != null){
actionBarsMenu.add(toggleTextWrapAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleTextAction);
actionBarsMenu.add(toggleListAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(cvsHistoryFilter);
actionBarsMenu.add(toggleFilterAction);
}
actionBars.updateActionBars();
}
}*/
| private void contributeActions() {
final IPreferenceStore store = TeamUIPlugin.getPlugin().getPreferenceStore();
//Group by Date
groupByDateMode = new Action(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY)){
public void run() {
groupingOn = !groupingOn;
store.setValue(IPreferenceIds.PREF_GROUPBYDATE_MODE, groupingOn);
refreshHistory(false);
}
};
groupingOn = store.getBoolean(IPreferenceIds.PREF_GROUPBYDATE_MODE);
groupByDateMode.setChecked(groupingOn);
groupByDateMode.setToolTipText(TeamUIMessages.LocalHistoryPage_GroupRevisionsByDateTip);
groupByDateMode.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
groupByDateMode.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_DATES_CATEGORY));
//Collapse All
collapseAll = new Action(TeamUIMessages.LocalHistoryPage_CollapseAllAction, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL)) {
public void run() {
treeViewer.collapseAll();
}
};
collapseAll.setToolTipText(TeamUIMessages.LocalHistoryPage_CollapseAllTip);
collapseAll.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
collapseAll.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COLLAPSE_ALL));
//Compare Mode Action
compareModeAction = new Action(TeamUIMessages.LocalHistoryPage_CompareModeAction,TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW)) {
public void run() {
compareMode = !compareMode;
compareModeAction.setChecked(compareMode);
}
};
compareModeAction.setToolTipText(TeamUIMessages.LocalHistoryPage_CompareModeTip);
compareModeAction.setDisabledImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setHoverImageDescriptor(TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_COMPARE_VIEW));
compareModeAction.setChecked(false);
// Click Compare action
compareAction = new CompareRevisionAction(TeamUIMessages.LocalHistoryPage_CompareAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
compareAction.setCurrentFileRevision(getCurrentFileRevision());
compareAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
compareAction.setPage(this);
openAction = new OpenRevisionAction(TeamUIMessages.LocalHistoryPage_OpenAction);
treeViewer.getTree().addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
openAction.selectionChanged((IStructuredSelection) treeViewer.getSelection());
}
});
openAction.setPage(this);
OpenStrategy handler = new OpenStrategy(treeViewer.getTree());
handler.addOpenListener(new IOpenEventListener() {
public void handleOpen(SelectionEvent e) {
StructuredSelection tableStructuredSelection = (StructuredSelection) treeViewer.getSelection();
if (compareMode){
StructuredSelection sel = new StructuredSelection(new Object[] {getCurrentFileRevision(), tableStructuredSelection.getFirstElement()});
compareAction.selectionChanged(sel);
compareAction.run();
} else {
//Pass in the entire structured selection to allow for multiple editor openings
StructuredSelection sel = tableStructuredSelection;
openAction.selectionChanged(sel);
openAction.run();
}
}
});
//Contribute actions to popup menu
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(treeViewer.getTree());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
treeViewer.getTree().setMenu(menu);
//Don't add the object contribution menu items if this page is hosted in a dialog
IHistoryPageSite parentSite = getHistoryPageSite();
/*if (!parentSite.isModal()) {
IWorkbenchPart part = parentSite.getPart();
if (part != null) {
IWorkbenchPartSite workbenchPartSite = part.getSite();
workbenchPartSite.registerContextMenu(menuMgr, treeViewer);
}
IPageSite pageSite = parentSite.getWorkbenchPageSite();
if (pageSite != null) {
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
if (actionBarsMenu != null){
actionBarsMenu.add(toggleTextWrapAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleTextAction);
actionBarsMenu.add(toggleListAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(cvsHistoryFilter);
actionBarsMenu.add(toggleFilterAction);
}
actionBars.updateActionBars();
}
}*/
|
diff --git a/src/com/reelfx/Applet.java b/src/com/reelfx/Applet.java
index 79b5318..79f76bc 100644
--- a/src/com/reelfx/Applet.java
+++ b/src/com/reelfx/Applet.java
@@ -1,661 +1,661 @@
package com.reelfx;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import netscape.javascript.JSException;
import netscape.javascript.JSObject;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.reelfx.controller.AbstractController;
import com.reelfx.controller.LinuxController;
import com.reelfx.controller.MacController;
import com.reelfx.controller.WindowsController;
import com.reelfx.model.AttributesManager;
import com.reelfx.model.CaptureViewport;
import com.reelfx.view.util.ViewListener;
import com.reelfx.view.util.ViewNotifications;
import com.sun.JarClassLoader;
/**
*
* The applet initializer class. It adheres to the standard Java applet, setups all a series of
* global variables used throughout the applet, acts as a middle man for the Java/Javascript
* communication, and provides a series of auxilary methods for unpacking JAR files, etc.
*
* @author Daniel Dixon (http://www.danieldixon.com)
*
*
* Copyright (C) 2010 ReelFX Creative Studios (http://www.reelfx.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*
* SPECIAL NOTE ON JSObject on Mac (Used for communicating with Javascript)
* In Eclipse, initially couldn't find the class. This guy said to add a reference to 'plugin.jar'
* (http://stackoverflow.com/questions/1664604/jsobject-download-it-or-available-in-jre-1-6) however
* the only plugin.jar's I found for Java via the 'locate plugin.jar' command were either bad symlinks or inside
* .bundle so I had to create a good symlink called plugin-daniel.jar in /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib
* that pointed to /System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/Deploy.bundle/Contents/Resources/Java/plugin.jar
* I had no issue adding it on Windows or Linux.
*
* Further information: http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/java_js.html
*/
public class Applet extends JApplet {
private static final long serialVersionUID = 4544354980928245103L;
public static File BASE_FOLDER, BIN_FOLDER, DESKTOP_FOLDER;
public static URL DOCUMENT_BASE, CODE_BASE;
public static JApplet APPLET;
public static JSObject JS_BRIDGE;
public static String POST_URL = null, SCREEN_CAPTURE_NAME = null, API_KEY, HOST_URL;
public static boolean HEADLESS = false;
public static boolean IS_MAC = System.getProperty("os.name").toLowerCase().contains("mac");
public static boolean IS_LINUX = System.getProperty("os.name").toLowerCase().contains("linux");
public static boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
public static boolean DEV_MODE = false;
public final static Dimension SCREEN = new Dimension( // for the primary monitor only
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth(),
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight());
public final static CaptureViewport CAPTURE_VIEWPORT = new CaptureViewport();
public static Vector<Window> APPLET_WINDOWS = new Vector<Window>(); // didn't want to manually manage windows, but Safari would only return a Frame through Window.getWindows() on commands called via JS
private AbstractController controller = null;
private static Logger logger = Logger.getLogger(Applet.class);
public static Properties PROPERTIES = new Properties(); // TODO move some of these static variables into the Properties obj? clean up properties in general?
/**
* The init method is called when this applet is loaded into the browser. It is used to initialize
* finish initializing all static variables used for state.
*/
@Override
public void init() {
try {
if(getParameter("dev_mode") != null)
- DEV_MODE = true;
+ DEV_MODE = getParameter("dev_mode").equals("true");
// setup properties configuration (should before base folder)
if(Applet.DEV_MODE) {
PROPERTIES.load(new FileInputStream("../config.properties"));
} else {
PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
}
BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
// setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709)
if(Applet.DEV_MODE) {
System.setProperty("log.file.path", "../logs/development.log");
PropertyConfigurator.configure("../logs/log4j.properties");
} else {
System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log");
PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
// setup the javascript API
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
logger.error("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
// verify that we have what we need
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath());
if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath());
// print information to console
logger.info(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (Exception e) {
logger.error("Could not create GUI!",e);
}
}
/**
* Sends a notification to all the views and each can update itself accordingly.
*
* @param notification
* @param body
*/
public static void sendViewNotification(ViewNotifications notification,Object body) {
// applet is a special case (see ApplicationController constructor)
if(APPLET.getContentPane().getComponents().length > 0)
((ViewListener) APPLET.getContentPane().getComponent(0)).receiveViewNotification(notification, body);
// another special case where the capture viewport is a pseudo-model
CAPTURE_VIEWPORT.receiveViewNotification(notification, body);
// notify all the open windows (tried Window.getWindows() but had issues)
for(Window win : Applet.APPLET_WINDOWS) {
if(win instanceof ViewListener) {
((ViewListener) win).receiveViewNotification(notification, body);
}
}
}
public static void sendViewNotification(ViewNotifications notification) {
sendViewNotification(notification, null);
}
// ---------- BEGIN INCOMING JAVASCRIPT API ----------
/**
* Allow an external interface trigger the count-down and subsequent recording
*/
public void prepareAndRecord() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
controller.recordGUI.prepareForRecording();
} catch (Exception e) {
logger.error("Can't prepare and start the recording!",e);
}
return null;
}
});
}
/**
* Allow an external interface top the recording
*/
public void stopRecording() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
controller.recordGUI.stopRecording();
} catch (Exception e) {
logger.error("Can't stop the recording!",e);
}
return null;
}
});
}
/**
* Allow an external interface to open the preview player
*/
public void previewRecording() {
controller.previewRecording();
}
/**
* Allow an external interface change where the final movie file is posted to
*/
public void changePostUrl(final String url) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
POST_URL = url;
logger.info("Changed post URL to "+url);
} catch (Exception e) {
logger.error("Can't change the post URL!",e);
}
return null;
}
});
}
/**
* Allow an external interface to post process and upload the recording
*/
public void postRecording() {
controller.postRecording();
}
/**
* Allow an external interface to show the recording interface
*/
public void showRecordingInterface() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null) {
if (AttributesManager.OUTPUT_FILE.exists()) {
handleExistingRecording();
logger.info("Outside call to show recording interface, but prior review exists...");
} else {
controller.showRecordingInterface();
logger.info("Outside call to show recording interface. Showing recording tools...");
}
}
else {
logger.error("No controller exists!");
}
}
});
} catch (Exception e) {
logger.error("Can't show the recording interface!",e);
}
return null;
}
});
}
/**
* Allow an external interface to hide the recording interface
*/
public void hideRecordingInterface() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.hideRecordingInterface();
}
});
} catch (Exception e) {
logger.error("Can't hide the recording interface!",e);
}
return null;
}
});
}
// ---------- END INCOMING / BEGIN OUTGOING JAVASCRIPT API ----------
public static void handleRecordingUpdate(ViewNotifications state,String status) {
if(status == null) status = "";
jsCall("sct_handle_recording_update(\""+state+"\",\""+status+"\");");
}
public static void handleRecordingUIHide() {
jsCall("sct_handle_recording_ui_hide();");
}
public static void handleExistingRecording() {
jsCall("sct_handle_existing_recording()");
}
public static void handleFreshRecording() {
jsCall("sct_handle_fresh_recording()");
}
public static void handleUploadedRecording() {
jsCall("sct_handle_uploaded_recording()");
}
public static void handleDeletedRecording() {
jsCall("sct_handle_deleted_recording()");
}
public static void redirectWebPage(String url) {
jsCall("sct_redirect_page(\""+url+"\");");
}
public static void sendShowStatus(String message) {
jsCall("sct_show_status(\""+message+"\");");
}
public static void sendHideStatus() {
jsCall("sct_hide_status();");
}
public static void sendInfo(String message) {
jsCall("sct_info(\""+message+"\");");
}
public static void sendError(String message) {
jsCall("sct_error(\""+message+"\");");
}
private static void jsCall(String method) {
if(JS_BRIDGE == null) {
logger.error("Call to "+method+" but no JS Bridge exists. Probably in development mode...");
} else {
//System.out.println("Sending javascript call: "+method);
//JSObject doc = (JSObject) JS_BRIDGE.getMember("document");
//doc.eval(method);
JS_BRIDGE.eval(method);
}
}
// ---------- END OUTGOING JAVASCRIPT API ----------
/**
* Copies an entire folder out of a jar to a physical location.
*
* Base code: http://forums.sun.com/thread.jspa?threadID=5154854
* Helpful: http://mindprod.com/jgloss/getresourceasstream.html
* Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file
*
* @param jarName Path and name of the jar to extract from
* @param folderName Single name, not path, of the folder to pull from the root of the jar.
*/
public static void copyFolderFromCurrentJar(String jarName, String folderName) {
if(jarName == null || folderName == null) return;
try {
ZipFile z = new ZipFile(jarName);
Enumeration<? extends ZipEntry> entries = z.entries();
// make the folder first
//File folder = new File(RFX_FOLDER.getAbsolutePath()+File.separator+folderName);
//if( !folder.exists() ) folder.mkdir();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.getName().contains(folderName)) {
File f = new File(BASE_FOLDER.getAbsolutePath()+File.separator+entry.getName());
if (entry.isDirectory() && f.mkdir()) {
logger.info("Created folder "+f.getAbsolutePath()+" for "+entry.getName());
}
else if (!f.exists()) {
if (copyFileFromJar(entry.getName(), f)) {
logger.info("Copied file: " + entry.getName());
} else {
logger.error("Could not copy file: "+entry.getName());
}
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Use this one or loading from a remote jar and extracting it.
*
* @param jar
* @param folderName
*/
public static void copyFolderFromRemoteJar(URL jar, String folderName) {
if(jar == null || folderName == null) return;
try {
JarClassLoader jarLoader = new JarClassLoader(jar);
URL u = new URL("jar", "", jar + "!/");
JarURLConnection uc = (JarURLConnection)u.openConnection();
JarFile jarFile = uc.getJarFile();
Enumeration<? extends JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.getName().contains(folderName)) {
File f = new File(BASE_FOLDER.getAbsolutePath()+File.separator+entry.getName());
if (entry.isDirectory() && f.mkdir()) {
logger.info("Created folder "+f.getAbsolutePath()+" for "+entry.getName());
}
else if (!f.exists()) {
if (copyFileFromJar(entry.getName(), f, jarLoader)) {
logger.info("Copied file: " + entry.getName());
} else {
logger.error("Could not copy file: "+entry.getName());
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
protected static boolean copyFileFromJar(String sResource, File fDest) {
return copyFileFromJar(sResource, fDest, Applet.class.getClassLoader());
}
/**
* Copies a file out of the jar to a physical location.
* Doesn't need to be private, uses a resource stream, so may have
* security errors if run from webstart application
*
* Base code: http://forums.sun.com/thread.jspa?threadID=5154854
* Helpful: http://mindprod.com/jgloss/getresourceasstream.html
* Helpful: http://stackoverflow.com/questions/810284/putting-bat-file-inside-a-jar-file
*/
protected static boolean copyFileFromJar(String sResource, File fDest, ClassLoader loader) {
if (sResource == null || fDest == null) return false;
InputStream sIn = null;
OutputStream sOut = null;
File sFile = null;
try {
fDest.getParentFile().mkdirs();
sFile = new File(sResource);
}
catch(Exception e) {
e.printStackTrace();
}
try {
int nLen = 0;
sIn = loader.getResourceAsStream(sResource);
if (sIn == null)
throw new IOException("Could not get resource as stream to copy " + sResource + " from the jar to " + fDest.getAbsolutePath() + ")");
sOut = new FileOutputStream(fDest);
byte[] bBuffer = new byte[1024];
while ((nLen = sIn.read(bBuffer)) > 0)
sOut.write(bBuffer, 0, nLen);
sOut.flush();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (sIn != null)
sIn.close();
if (sOut != null)
sOut.close();
}
catch (IOException eError) {
eError.printStackTrace();
}
}
return fDest.exists();
}
/**
* Print out information the configuration the Applet is running under.
*
* base code: http://stackoverflow.com/questions/2234476/how-to-detect-the-current-display-with-java
*/
@Override
public String getAppletInfo() {
// screen the Applet is on
GraphicsDevice myScreen = getGraphicsConfiguration().getDevice();
// screen the start bar, OS bar, whatever is on
GraphicsDevice primaryScreen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
// all screens
GraphicsDevice[] allScreens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
int myScreenIndex = -1, primaryScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
if (allScreens[i].equals(myScreen))
{
myScreenIndex = i;
}
if (allScreens[i].equals(primaryScreen))
{
primaryScreenIndex = i;
}
}
try {
return
"\n\n\n\nAPPLET PROPERLY INITIALIZED WITH THIS VARIABLES:\n"+
"Java Version: \t"+System.getProperty("java.version")+"\n"+
"OS Name: \t"+System.getProperty("os.name")+"\n"+
"OS Version: \t"+System.getProperty("os.version")+"\n"+
"Dev Mode? \t"+DEV_MODE+"\n"+
"Run Directory: \t"+System.getProperty("user.dir")+"\n"+
"User Home: \t"+System.getProperty("user.home")+"\n"+
"User Name: \t"+System.getProperty("user.name")+"\n"+
"Base Folder: \t"+BASE_FOLDER.getPath()+"\n"+
"Bin Folder: \t"+BIN_FOLDER.getPath()+"\n"+
"User Desktop: \t"+DESKTOP_FOLDER.getPath()+"\n"+
"Host URL:\t"+HOST_URL+"\n"+
"Code Base: \t"+getCodeBase()+"\n"+
"Document Base: \t"+getDocumentBase()+"\n"+
"Execution URL: \t"+Applet.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()+"\n"+
"Multiple Monitors: \t"+(allScreens.length > 1)+"\n"+
"Applet window is on screen " + myScreenIndex+"\n"+
"Primary screen is index " + primaryScreenIndex+"\n"+
"Primary screen resolution: "+SCREEN+"\n"+
"Headless: \t"+HEADLESS;
} catch (URISyntaxException e) {
e.printStackTrace();
return "Error";
}
/*
System.out.println("Have these system variables:");
Map<String, String> sysEnv = System.getenv();
for (String envName : sysEnv.keySet()) {
System.out.format("%s=%s%n", envName, sysEnv.get(envName));
}
*/
//System.out.println("Free space: \n"+TEMP_FOLDER.getFreeSpace()+" GBs"); // Java 1.6 only
//System.out.println("Total space: \n"+TEMP_FOLDER.getTotalSpace()+" GBs");
}
/**
* The "base" folder is where all preference files and media files are recorded.
*
* @return
* @throws IOException
*/
public static String getBaseFolderPath() throws IOException {
if(IS_MAC)
return System.getProperty("user.home")+File.separator+"Library"+File.separator+PROPERTIES.getProperty("base.folder");
else if(IS_LINUX)
return System.getProperty("user.home")+File.separator+"."+PROPERTIES.getProperty("base.folder");
else if(IS_WINDOWS)
return System.getenv("TEMP")+File.separator+PROPERTIES.getProperty("base.folder");
else
throw new IOException("I don't know where to find the native extensions!");
}
/**
* The "bin" folder is where the binaries are downloaded to and execute from.
*
* @return
* @throws IOException
*/
public static String getBinFolderPath() throws IOException {
return BASE_FOLDER.getAbsolutePath()+File.separator+getBinFolderName();
}
/**
* These must start with "bin".
*
* @return Name of folder and JAR with folder of same name for holding native extensions.
* @throws IOException
*/
public static String getBinFolderName() throws IOException {
if(IS_MAC)
return "bin-mac";
else if(IS_LINUX)
return "bin-linux";
else if(IS_WINDOWS)
return "bin-windows-v1.2";
else
throw new IOException("I don't know what bin folder to use!");
}
/**
* Determines the desktop folder for the machine that the Java applet is running on. Not tested, and not used.
* @return
* @throws IOException
*/
public static String getDesktopFolderPath() throws IOException {
if(IS_MAC || IS_LINUX || IS_WINDOWS)
return System.getProperty("user.home")+File.separator+"Desktop";
else
throw new IOException("I don't know where to find the user's desktop!");
}
/**
* Called when the browser closes the web page.
*
* NOTE: A bug in Mac OS X may prevent this from being called: http://lists.apple.com/archives/java-dev///2009/Oct/msg00042.html
*/
@Override
public void destroy() {
System.out.println("Closing down...");
if(controller != null)
controller.closeDown();
controller = null;
}
}
| true | true | public void init() {
try {
if(getParameter("dev_mode") != null)
DEV_MODE = true;
// setup properties configuration (should before base folder)
if(Applet.DEV_MODE) {
PROPERTIES.load(new FileInputStream("../config.properties"));
} else {
PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
}
BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
// setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709)
if(Applet.DEV_MODE) {
System.setProperty("log.file.path", "../logs/development.log");
PropertyConfigurator.configure("../logs/log4j.properties");
} else {
System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log");
PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
// setup the javascript API
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
logger.error("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
// verify that we have what we need
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath());
if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath());
// print information to console
logger.info(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (Exception e) {
logger.error("Could not create GUI!",e);
}
}
| public void init() {
try {
if(getParameter("dev_mode") != null)
DEV_MODE = getParameter("dev_mode").equals("true");
// setup properties configuration (should before base folder)
if(Applet.DEV_MODE) {
PROPERTIES.load(new FileInputStream("../config.properties"));
} else {
PROPERTIES.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
}
BASE_FOLDER = new File(getBaseFolderPath()); // should be next, after property loading
BIN_FOLDER = new File(getBinFolderPath());
DESKTOP_FOLDER = new File(getDesktopFolderPath());
// setup logging (http://www.theserverside.com/discussions/thread.tss?thread_id=42709)
if(Applet.DEV_MODE) {
System.setProperty("log.file.path", "../logs/development.log");
PropertyConfigurator.configure("../logs/log4j.properties");
} else {
System.setProperty("log.file.path", BASE_FOLDER.getAbsolutePath()+File.separator+"production.log");
PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
// setup the javascript API
try {
JS_BRIDGE = JSObject.getWindow(this);
} catch(JSException e) {
logger.error("Could not create JSObject. Probably in development mode.");
}
DOCUMENT_BASE = getDocumentBase();
CODE_BASE = getCodeBase();
APPLET = this; // breaking OOP so I can have a "root"
POST_URL = getParameter("post_url");
API_KEY = getParameter("api_key");
SCREEN_CAPTURE_NAME = getParameter("screen_capture_name");
HOST_URL = DOCUMENT_BASE.getProtocol() + "://" + DOCUMENT_BASE.getHost();
// verify that we have what we need
if(getParameter("headless") != null)
HEADLESS = !getParameter("headless").isEmpty() && getParameter("headless").equals("true"); // Boolean.getBoolean(string) didn't work
if( BASE_FOLDER.exists() && !BASE_FOLDER.isDirectory() && !BASE_FOLDER.delete() )
throw new IOException("Could not delete file for folder: " + BASE_FOLDER.getAbsolutePath());
if( !BASE_FOLDER.exists() && !BASE_FOLDER.mkdir() )
throw new IOException("Could not create folder: " + BASE_FOLDER.getAbsolutePath());
// print information to console
logger.info(getAppletInfo());
// execute a job on the event-dispatching thread; creating this applet's GUI
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// start up the os-specific controller
if(IS_MAC)
controller = new MacController();
else if(IS_LINUX)
controller = new LinuxController();
else if(IS_WINDOWS)
controller = new WindowsController();
else
System.err.println("Want to launch controller but don't which operating system this is!");
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(controller != null)
controller.setupExtensions();
}
});
} catch (Exception e) {
logger.error("Could not create GUI!",e);
}
}
|
diff --git a/app/controllers/DataHub.java b/app/controllers/DataHub.java
index 61f165b..0db5023 100644
--- a/app/controllers/DataHub.java
+++ b/app/controllers/DataHub.java
@@ -1,315 +1,315 @@
package controllers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import nl.bitwalker.useragentutils.UserAgent;
import com.mongodb.MongoException;
import models.RecordedLocation;
import models.TrackSession;
import models.TrackedAction;
import models.User;
import play.Play;
import play.data.Form;
import play.data.validation.Constraints.Required;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.Context;
import play.mvc.Http.Cookie;
import play.mvc.Result;
import utils.Base64;
import utils.Tools;
public class DataHub extends Controller {
public static class TrackRequest {
@Required
public String d;
@Required
public String host;
@Required
public String key;
}
public static Result track() {
response().setContentType( "image/png" );
InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png");
Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest();
if( req.hasErrors() ) return badRequest( outGifStream );
TrackSession.Model trackSess = null;
User.Model user = null;
try {
user = User.coll.findOneById( req.get().key );
} catch( MongoException e ) {
e.printStackTrace();
return internalServerError("No User");
}
if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream );
if( !User.isDomainTrackable( req.get().host, user ) ) {
return forbidden( outGifStream );
}
Long systemTs = new Date().getTime();
- if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") )
+// if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") )
if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") &&
( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) &&
session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) {
trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") );
} else {
trackSess = new TrackSession.Model();
trackSess.startedAt = new Date();
if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) {
trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0];
UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent );
trackSess.os = userAgent.getOperatingSystem().name();
trackSess.browser = userAgent.getBrowser().name();
}
if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) {
trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0];
String[] languages = trackSess.language.split(",");
if( languages.length > 1 ) trackSess.mainLanguage = languages[0];
else trackSess.mainLanguage = trackSess.language;
}
trackSess.host = req.get().host;
trackSess.userId = user._id;
trackSess._id = TrackSession.save(trackSess).getSavedId();
session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id);
//TODO: get client IP using http proxy
}
RecordedLocation.Model loc = null;
if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) {
loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") );
}
String actionsString = new String( Base64.decode( req.get().d ) );
String[] actions = actionsString.split("}");
Long lastTs = 0L;
for(int i = 0; i < actions.length; i++) {
String[] parts = actions[i].split("[|]");
if( parts.length < 1 ) continue;
TrackedAction.Model action = null;
try {
switch( Byte.valueOf( parts[0] ) ) {
case 0:
if( parts.length != 7 ) continue;
//TODO:Track domains and pageUrl
action = new TrackedAction.Model();
action.e = 0;
action.location = parts[1];
action.w = Short.valueOf( parts[2] );
action.h = Short.valueOf( parts[3] );
action.t = Short.valueOf( parts[4] );
action.l = Short.valueOf( parts[5] );
action.ts = Long.valueOf( parts[6] );
loc = new RecordedLocation.Model();
loc.sessionId = trackSess._id;
loc.startedAt = new Date( action.ts );
loc.location = parts[1];
loc._id = RecordedLocation.save( loc ).getSavedId();
if( trackSess.firstActionAt == null ) {
trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess);
}
session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id);
break;
case 1: //mouse down
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 1;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 2: //move
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 2;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 3: //resize
if( parts.length != 4 ) continue;
action = new TrackedAction.Model();
action.e = 3;
action.w = Short.valueOf( parts[1] );
action.h = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 4: //scroll
if( parts.length != 5 ) continue;
action = new TrackedAction.Model();
action.e = 4;
action.t = Short.valueOf( parts[1] );
action.l = Short.valueOf( parts[2] );
action.d = parts[3];
action.ts = Long.valueOf( parts[4] );
break;
case 5:
break;
}
} catch(NumberFormatException e) {
continue;
}
if( action != null ) {
action.recLocId = loc._id;
TrackedAction.save(action);
lastTs = action.ts;
}
}
if( lastTs > 0 ) {
loc.lastActionAt = new Date( lastTs );
trackSess.lastActionAt = new Date( lastTs );
TrackSession.save( trackSess );
}
RecordedLocation.save( loc );
session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+"");
response().setContentType( "image/png" );
return ok( outGifStream );
}
public static Result dummy() {/*
Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest();
List<String> dummy = new ArrayList<String>();
dummy.add( "0|http://localhost/work/we3c/static/barebone.html#|1600|503|0|0|1339451636005}2|538|292|1339451636828}2|66|494|1339451638213}2|42|66|1339451638366}2|480|3|1339451638586}2|773|283|1339451638927}1|781|290|1339451639133}2|860|309|1339451639287}2|904|309|1339451639304}2|942|313|1339451639319}2|980|313|1339451639336}2|993|315|1339451639341}2|1350|261|1339451639607}1|1351|260|1339451639706}2|1346|260|1339451639874}2|1253|253|1339451639927}2|1230|255|1339451639935}2|881|246|1339451640021}2|860|249|1339451640033}2|762|247|1339451640078}2|691|275|1339451640209}2|680|275|1339451640225}2|654|278|1339451640271}4|2|0||1339451640322}4|128|0|d|1339451640701}2|563|384|1339451641061}2|532|382|1339451641156}2|523|383|1339451641227}2|485|375|1339451641382}2|398|467|1339451641476}2|369|467|1339451641586}2|340|471|1339451641820}1|339|471|1339451641849}2|336|470|1339451641976}2|227|464|1339451642029}2|198|466|1339451642038}2|0|295|1339451642186}2|218|241|1339451642505}2|470|277|1339451642569}2|503|277|1339451642577}2|532|279|1339451642585}2|557|279|1339451642591}2|744|310|1339451642663}2|759|310|1339451642672}2|783|315|1339451642686}2|796|315|1339451642694}2|807|320|1339451642701}2|816|320|1339451642712}2|979|398|1339451642935}2|1121|228|1339451643077}2|1121|205|1339451643085}2|1126|171|1339451643099}2|1126|136|1339451643123}2|715|236|1339451643381}2|574|233|1339451643405}2|523|235|1339451643413}2|443|232|1339451643427}2|408|234|1339451643435}2|314|201|1339451643529}2|316|186|1339451643537}" );
dummy.add( "2|318|165|1339451643554}2|438|60|1339451643664}2|902|266|1339451644115}2|1195|259|1339451644269}4|125|0||1339451645048}4|2|0|t|1339451645366}2|1191|266|1339451645385}4|0|0||1339451645386}2|1185|266|1339451645421}2|1075|263|1339451645460}2|1040|265|1339451645468}2|1007|265|1339451645476}2|974|267|1339451645483}2|861|261|1339451645508}2|746|268|1339451645530}2|680|268|1339451645552}2|603|276|1339451645570}2|580|276|1339451645578}2|525|288|1339451645600}2|514|288|1339451645608}2|503|291|1339451645616}2|494|291|1339451645624}2|389|352|1339451645906}2|376|352|1339451645922}2|362|355|1339451645944}2|340|355|1339451645976}2|331|356|1339451646008}1|331|357|1339451646055}2|328|351|1339451646202}2|200|77|1339451646319}2|216|67|1339451646397}2|479|265|1339451646693}1|482|265|1339451646765}2|758|418|1339451647091}2|795|418|1339451647115}2|888|436|1339451647366}2|925|436|1339451647390}2|936|439|1339451647397}2|1009|425|1339451647585}1|1014|423|1339451647643}2|1249|195|1339451648099}2|1249|185|1339451648132}1|1248|178|1339451648215}2|736|147|1339451648521}2|713|149|1339451648529}2|521|143|1339451648639}2|209|356|1339451648921}2|200|356|1339451648928}2|149|364|1339451648992}2|117|331|1339451649123}2|301|229|1339451649257}2|619|369|1339451649553}2|1093|172|1339451649873}2|1093|163|1339451649881}2|1098|151|1339451649889}2|1098|142|1339451649897}2|1116|120|1339451649959}2|1253|172|1339451650077}2|1014|246|1339451650311}2|989|246|1339451650319}" );
dummy.add( "2|945|243|1339451650336}2|497|134|1339451650521}2|488|136|1339451650529}2|479|136|1339451650537}2|470|138|1339451650545}2|459|138|1339451650561}2|405|174|1339451650663}2|386|174|1339451650717}2|291|306|1339451651099}2|349|353|1339451651397}2|367|353|1339451651413}2|379|357|1339451651421}2|398|357|1339451651427}2|468|370|1339451651459}2|487|370|1339451651474}2|529|375|1339451651483}2|569|375|1339451651499}2|588|378|1339451651505}2|609|378|1339451651513}2|653|383|1339451651529}2|699|383|1339451651545}2|722|385|1339451651553}2|743|385|1339451651561}2|766|387|1339451651574}2|1268|277|1339451651913}2|1253|174|1339451652007}2|1257|156|1339451652093}2|1042|407|1339451652295}2|301|238|1339451652671}2|709|177|1339451652857}2|718|180|1339451652865}2|727|180|1339451652874}2|1099|322|1339451653030}2|1130|322|1339451653037}2|1161|324|1339451653045}2|1324|277|1339451653139}2|1324|265|1339451653147}2|1326|253|1339451653155}2|1326|216|1339451653171}2|1328|203|1339451653177}2|1328|146|1339451653201}2|1332|128|1339451653217}2|1322|105|1339451653373}2|856|238|1339451653499}2|417|159|1339451653663}4|5|0||1339451653815}2|414|153|1339451653836}4|20|0||1339451653844}2|414|154|1339451653861}4|40|0||1339451653866}4|51|0|d|1339451653879}2|415|154|1339451653897}4|64|0||1339451653900}2|415|155|1339451653920}4|78|0||1339451653923}2|414|158|1339451653938}4|87|0||1339451653940}2|413|161|1339451653949}4|95|0||1339451653957}2|410|165|1339451653972}" );
dummy.add( "4|105|0||1339451653981}2|409|173|1339451653995}4|112|0||1339451654002}2|409|175|1339451654008}4|121|0||1339451654029}2|409|178|1339451654038}4|124|0||1339451654039}4|128|0|d|1339451654078}2|409|179|1339451654233}2|439|190|1339451654358}2|448|190|1339451654406}4|125|0||1339451654495}2|456|190|1339451654510}4|110|0||1339451654520}4|73|0|t|1339451654564}2|460|190|1339451654581}4|61|0||1339451654583}2|462|190|1339451654587}4|48|0||1339451654611}2|469|192|1339451654617}4|42|0||1339451654618}4|37|0|t|1339451654631}2|471|192|1339451654635}4|31|0||1339451654647}2|474|192|1339451654650}4|26|0||1339451654663}2|477|193|1339451654666}4|19|0||1339451654684}2|480|193|1339451654685}4|14|0||1339451654700}2|481|193|1339451654702}4|10|0||1339451654716}2|487|193|1339451654719}4|7|0||1339451654732}2|518|193|1339451654753}4|3|0||1339451654754}2|550|186|1339451654763}4|1|0||1339451654770}2|594|186|1339451654779}4|0|0||1339451654787}2|877|2|1339451654881}3|1541|496|1339451655809}2|932|14|1339451656029}2|934|26|1339451656037}2|934|41|1339451656045}2|1147|303|1339451656257}2|1192|303|1339451656327}2|1226|309|1339451656373}2|1268|309|1339451656421}2|1304|318|1339451656492}3|1163|496|1339451656805}2|862|313|1339451657217}2|871|313|1339451657398}3|1454|496|1339451657683}2|1210|291|1339451658091}2|948|222|1339451658427}4|2|0||1339451658434}2|947|222|1339451658439}4|9|0||1339451658456}4|27|0|d|1339451658485}" );
dummy.add( "2|945|222|1339451658516}4|61|0||1339451658524}4|114|0|d|1339451658638}2|943|222|1339451658652}4|121|0||1339451658655}4|135|0|d|1339451658730}4|43|0|t|1339451659112}2|946|223|1339451659116}4|30|0||1339451659136}2|948|227|1339451659144}4|23|0||1339451659151}2|951|229|1339451659163}4|17|0||1339451659166}2|953|230|1339451659179}4|12|0||1339451659181}2|957|231|1339451659185}4|7|0||1339451659197}2|963|234|1339451659201}2|972|240|1339451659213}4|3|0||1339451659214}2|1000|255|1339451659230}4|1|0||1339451659231}2|1029|272|1339451659241}4|0|0||1339451659247}2|1124|306|1339451659295}3|1012|496|1339451659696}2|584|277|1339451659897}2|555|273|1339451659999}4|2|0||1339451660501}4|135|0|d|1339451660783}2|552|272|1339451661062}4|134|0||1339451661182}4|20|0|t|1339451661378}2|555|271|1339451661398}4|14|0||1339451661400}2|559|272|1339451661405}4|10|0||1339451661417}2|572|275|1339451661419}4|7|0||1339451661433}2|588|279|1339451661435}2|604|282|1339451661443}4|4|0||1339451661449}2|633|285|1339451661459}4|2|0||1339451661466}2|663|293|1339451661475}4|0|0||1339451661482}2|774|335|1339451661655}3|1454|496|1339451661994}2|1250|340|1339451662349}2|572|191|1339451662607}2|532|195|1339451662624}2|496|195|1339451662639}2|421|228|1339451662749}4|3|0||1339451662793}2|423|234|1339451662796}4|18|0||1339451662820}4|47|0|d|1339451662853}2|425|238|1339451662869}4|62|0||1339451662877}2|427|239|1339451662891}" );
dummy.add( "4|78|0||1339451662900}2|428|241|1339451662914}4|88|0||1339451662922}2|430|244|1339451662937}4|103|0||1339451662948}2|431|245|1339451662955}4|119|0||1339451662996}2|435|253|1339451663017}4|128|0||1339451663021}4|135|0|d|1339451663069}2|436|253|1339451663258}4|129|0||1339451663270}2|437|253|1339451663279}4|117|0||1339451663289}2|440|254|1339451663298}4|102|0||1339451663305}2|445|255|1339451663316}4|89|0||1339451663321}2|450|255|1339451663327}4|65|0||1339451663355}2|457|256|1339451663373}4|52|0||1339451663379}2|462|256|1339451663395}4|42|0||1339451663399}2|466|256|1339451663415}4|34|0||1339451663417}2|474|256|1339451663425}4|30|0||1339451663430}2|482|255|1339451663440}4|26|0||1339451663442}2|489|255|1339451663449}4|22|0||1339451663455}2|496|252|1339451663460}2|510|240|1339451663484}4|14|0||1339451663489}2|525|224|1339451663503}4|8|0||1339451663506}2|538|205|1339451663513}4|6|0||1339451663518}2|552|180|1339451663530}4|4|0||1339451663532}2|562|150|1339451663545}4|2|0||1339451663547}2|572|123|1339451663564}4|0|0||1339451663565}2|580|63|1339451663591}2|580|50|1339451663599}2|609|5|1339451663718}3|1600|503|1339451664560}2|605|5|1339451664763}2|573|140|1339451664881}1|573|147|1339451664969}2|497|280|1339451665193}2|467|280|1339451665209}2|437|285|1339451665225}2|422|285|1339451665233}2|343|335|1339451665390}1|336|337|1339451665493}2|338|336|1339451665647}2|385|332|1339451665673}" );
// System.out.println( Context.current().request().headers().get("USER-AGENT")[0] );
// System.out.println( Context.current().request().headers().get("ACCEPT-LANGUAGE")[0] );
// System.out.println( Context.current().request().headers().get("CONNECTION")[0] );
// System.out.println( Context.current().request().headers().get("ACCEPT")[0] );
// System.out.println( Context.current().request().host() );
// System.out.println( Context.current().request().method() );
// System.out.println( Context.current().request().path() );
// System.out.println( Context.current().request().uri() );
// System.out.println( Context.current().request().acceptLanguages() );
// System.out.println( Context.current().request().queryString() );
TrackSession trackSess = null;
//TODO:Track Api Keys && Domains
if( session().containsKey("tracked_session") ) {
trackSess = TrackSession.coll.findOneById( session().get("tracked_session") );
} else {
trackSess = new TrackSession();
trackSess.startedAt = new Date();
if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0];
if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0];
trackSess.host = Context.current().request().host();
trackSess.userId = "4fdbb93244ae12efb6839f8d";
trackSess._id = trackSess.save().getSavedId();
session().put("tracked_session", trackSess._id);
//TODO: get client IP using http proxy
}
RecordedLocation loc = null;
if( session().containsKey("last_tracked_location") ) {
loc = RecordedLocation.coll.findOneById( session().get("last_tracked_location") );
}
for(int j = 0; j < dummy.size(); j++ ) {
String[] actions = dummy.get(j).split("}");
Long lastTs = 0L;
for(int i = 0; i < actions.length; i++) {
String[] parts = actions[i].split("[|]");
if( parts.length < 1 ) continue;
TrackedAction action = null;
try {
switch( Byte.valueOf( parts[0] ) ) {
case 0:
if( parts.length != 7 ) continue;
//TODO:Track domains and pageUrl
action = new TrackedAction();
action.e = 0;
action.location = parts[1];
action.w = Short.valueOf( parts[2] );
action.h = Short.valueOf( parts[3] );
action.t = Short.valueOf( parts[4] );
action.l = Short.valueOf( parts[5] );
action.ts = Long.valueOf( parts[6] );
loc = new RecordedLocation();
loc.sessionId = trackSess._id;
loc.startedAt = new Date( action.ts );
loc.location = parts[1];
loc._id = loc.save().getSavedId();
break;
case 1:
if( parts.length != 4 ) continue;
action = new TrackedAction();
action.e = 1;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 2:
if( parts.length != 4 ) continue;
action = new TrackedAction();
action.e = 2;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 3:
if( parts.length != 4 ) continue;
action = new TrackedAction();
action.e = 3;
action.w = Short.valueOf( parts[1] );
action.h = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 4:
if( parts.length != 5 ) continue;
action = new TrackedAction();
action.e = 4;
action.t = Short.valueOf( parts[1] );
action.l = Short.valueOf( parts[2] );
action.d = parts[3];
action.ts = Long.valueOf( parts[4] );
break;
case 5:
break;
}
} catch(NumberFormatException e) {
continue;
}
if( action != null ) {
action.recLocId = loc._id;
action.save();
lastTs = action.ts;
}
}
if( lastTs > 0 ) {
loc.lastActionAt = new Date( lastTs );
trackSess.lastActionAt = new Date( lastTs );
trackSess.save();
}
loc.save();
}*/
return ok();
}
}
| true | true | public static Result track() {
response().setContentType( "image/png" );
InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png");
Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest();
if( req.hasErrors() ) return badRequest( outGifStream );
TrackSession.Model trackSess = null;
User.Model user = null;
try {
user = User.coll.findOneById( req.get().key );
} catch( MongoException e ) {
e.printStackTrace();
return internalServerError("No User");
}
if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream );
if( !User.isDomainTrackable( req.get().host, user ) ) {
return forbidden( outGifStream );
}
Long systemTs = new Date().getTime();
if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") )
if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") &&
( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) &&
session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) {
trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") );
} else {
trackSess = new TrackSession.Model();
trackSess.startedAt = new Date();
if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) {
trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0];
UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent );
trackSess.os = userAgent.getOperatingSystem().name();
trackSess.browser = userAgent.getBrowser().name();
}
if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) {
trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0];
String[] languages = trackSess.language.split(",");
if( languages.length > 1 ) trackSess.mainLanguage = languages[0];
else trackSess.mainLanguage = trackSess.language;
}
trackSess.host = req.get().host;
trackSess.userId = user._id;
trackSess._id = TrackSession.save(trackSess).getSavedId();
session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id);
//TODO: get client IP using http proxy
}
RecordedLocation.Model loc = null;
if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) {
loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") );
}
String actionsString = new String( Base64.decode( req.get().d ) );
String[] actions = actionsString.split("}");
Long lastTs = 0L;
for(int i = 0; i < actions.length; i++) {
String[] parts = actions[i].split("[|]");
if( parts.length < 1 ) continue;
TrackedAction.Model action = null;
try {
switch( Byte.valueOf( parts[0] ) ) {
case 0:
if( parts.length != 7 ) continue;
//TODO:Track domains and pageUrl
action = new TrackedAction.Model();
action.e = 0;
action.location = parts[1];
action.w = Short.valueOf( parts[2] );
action.h = Short.valueOf( parts[3] );
action.t = Short.valueOf( parts[4] );
action.l = Short.valueOf( parts[5] );
action.ts = Long.valueOf( parts[6] );
loc = new RecordedLocation.Model();
loc.sessionId = trackSess._id;
loc.startedAt = new Date( action.ts );
loc.location = parts[1];
loc._id = RecordedLocation.save( loc ).getSavedId();
if( trackSess.firstActionAt == null ) {
trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess);
}
session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id);
break;
case 1: //mouse down
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 1;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 2: //move
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 2;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 3: //resize
if( parts.length != 4 ) continue;
action = new TrackedAction.Model();
action.e = 3;
action.w = Short.valueOf( parts[1] );
action.h = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 4: //scroll
if( parts.length != 5 ) continue;
action = new TrackedAction.Model();
action.e = 4;
action.t = Short.valueOf( parts[1] );
action.l = Short.valueOf( parts[2] );
action.d = parts[3];
action.ts = Long.valueOf( parts[4] );
break;
case 5:
break;
}
} catch(NumberFormatException e) {
continue;
}
if( action != null ) {
action.recLocId = loc._id;
TrackedAction.save(action);
lastTs = action.ts;
}
}
if( lastTs > 0 ) {
loc.lastActionAt = new Date( lastTs );
trackSess.lastActionAt = new Date( lastTs );
TrackSession.save( trackSess );
}
RecordedLocation.save( loc );
session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+"");
response().setContentType( "image/png" );
return ok( outGifStream );
}
| public static Result track() {
response().setContentType( "image/png" );
InputStream outGifStream = Play.application().resourceAsStream("/public/images/site/blank.png");
Form<TrackRequest> req = form( TrackRequest.class ).bindFromRequest();
if( req.hasErrors() ) return badRequest( outGifStream );
TrackSession.Model trackSess = null;
User.Model user = null;
try {
user = User.coll.findOneById( req.get().key );
} catch( MongoException e ) {
e.printStackTrace();
return internalServerError("No User");
}
if( user == null || user._id == null || user._id.isEmpty() ) return badRequest( outGifStream );
if( !User.isDomainTrackable( req.get().host, user ) ) {
return forbidden( outGifStream );
}
Long systemTs = new Date().getTime();
// if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") )
if( session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session_ts") &&
( systemTs < Integer.parseInt( session().get(Tools.md5Encode( req.get().host )+"_tracked_session_ts") ) ) &&
session().containsKey(Tools.md5Encode( req.get().host )+"_tracked_session") ) {
trackSess = TrackSession.coll.findOneById( session().get( Tools.md5Encode( req.get().host )+"_tracked_session") );
} else {
trackSess = new TrackSession.Model();
trackSess.startedAt = new Date();
if( Context.current().request().headers().containsKey("USER-AGENT") && Context.current().request().headers().get("USER-AGENT").length > 0 ) {
trackSess.userAgent = Context.current().request().headers().get("USER-AGENT")[0];
UserAgent userAgent = UserAgent.parseUserAgentString( trackSess.userAgent );
trackSess.os = userAgent.getOperatingSystem().name();
trackSess.browser = userAgent.getBrowser().name();
}
if( Context.current().request().headers().containsKey("ACCEPT-LANGUAGE") && Context.current().request().headers().get("ACCEPT-LANGUAGE").length > 0 ) {
trackSess.language = Context.current().request().headers().get("ACCEPT-LANGUAGE")[0];
String[] languages = trackSess.language.split(",");
if( languages.length > 1 ) trackSess.mainLanguage = languages[0];
else trackSess.mainLanguage = trackSess.language;
}
trackSess.host = req.get().host;
trackSess.userId = user._id;
trackSess._id = TrackSession.save(trackSess).getSavedId();
session().put( Tools.md5Encode( req.get().host )+"_tracked_session", trackSess._id);
//TODO: get client IP using http proxy
}
RecordedLocation.Model loc = null;
if( session().containsKey(Tools.md5Encode( req.get().host )+"_last_tracked_location") ) {
loc = RecordedLocation.coll.findOneById( session().get(Tools.md5Encode( req.get().host )+"_last_tracked_location") );
}
String actionsString = new String( Base64.decode( req.get().d ) );
String[] actions = actionsString.split("}");
Long lastTs = 0L;
for(int i = 0; i < actions.length; i++) {
String[] parts = actions[i].split("[|]");
if( parts.length < 1 ) continue;
TrackedAction.Model action = null;
try {
switch( Byte.valueOf( parts[0] ) ) {
case 0:
if( parts.length != 7 ) continue;
//TODO:Track domains and pageUrl
action = new TrackedAction.Model();
action.e = 0;
action.location = parts[1];
action.w = Short.valueOf( parts[2] );
action.h = Short.valueOf( parts[3] );
action.t = Short.valueOf( parts[4] );
action.l = Short.valueOf( parts[5] );
action.ts = Long.valueOf( parts[6] );
loc = new RecordedLocation.Model();
loc.sessionId = trackSess._id;
loc.startedAt = new Date( action.ts );
loc.location = parts[1];
loc._id = RecordedLocation.save( loc ).getSavedId();
if( trackSess.firstActionAt == null ) {
trackSess.firstActionAt = new Date( action.ts ); TrackSession.save(trackSess);
}
session().put(Tools.md5Encode( req.get().host )+"_last_tracked_location", loc._id);
break;
case 1: //mouse down
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 1;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 2: //move
if( parts.length != 6 ) continue;
action = new TrackedAction.Model();
action.e = 2;
action.x = Short.valueOf( parts[1] );
action.y = Short.valueOf( parts[2] );
action.w = Short.valueOf( parts[3] );
action.h = Short.valueOf( parts[4] );
action.ts = Long.valueOf( parts[5] );
break;
case 3: //resize
if( parts.length != 4 ) continue;
action = new TrackedAction.Model();
action.e = 3;
action.w = Short.valueOf( parts[1] );
action.h = Short.valueOf( parts[2] );
action.ts = Long.valueOf( parts[3] );
break;
case 4: //scroll
if( parts.length != 5 ) continue;
action = new TrackedAction.Model();
action.e = 4;
action.t = Short.valueOf( parts[1] );
action.l = Short.valueOf( parts[2] );
action.d = parts[3];
action.ts = Long.valueOf( parts[4] );
break;
case 5:
break;
}
} catch(NumberFormatException e) {
continue;
}
if( action != null ) {
action.recLocId = loc._id;
TrackedAction.save(action);
lastTs = action.ts;
}
}
if( lastTs > 0 ) {
loc.lastActionAt = new Date( lastTs );
trackSess.lastActionAt = new Date( lastTs );
TrackSession.save( trackSess );
}
RecordedLocation.save( loc );
session().put(Tools.md5Encode( req.get().host )+"_tracked_session_ts", ( systemTs + 3600000 )+"");
response().setContentType( "image/png" );
return ok( outGifStream );
}
|
diff --git a/src/ru/spbau/bioinf/evalue/SquareSearch.java b/src/ru/spbau/bioinf/evalue/SquareSearch.java
index 909f91a..2bc18a2 100644
--- a/src/ru/spbau/bioinf/evalue/SquareSearch.java
+++ b/src/ru/spbau/bioinf/evalue/SquareSearch.java
@@ -1,47 +1,47 @@
package ru.spbau.bioinf.evalue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import ru.spbau.bioinf.tagfinder.Configuration;
import ru.spbau.bioinf.tagfinder.Scan;
public class SquareSearch {
private static Logger log = Logger.getLogger(SquareSearch.class);
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
EValueServer.init(args);
Map<Integer,Scan> scans = conf.getScans();
DbUtil.initDatabase();
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Integer> proteinIds = new ArrayList<Integer>();
try {
ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)");
rs = ps.executeQuery();
while (rs.next()) {
proteinIds.add(rs.getInt(1));
}
} catch (SQLException e) {
log.error("Error loading proteins from database", e);
throw new RuntimeException(e);
} finally {
DbUtil.close(con, ps, rs);
}
for (Integer proteinId : proteinIds) {
- log.debug("Processing protein " + proteinId);
+ System.out.println("Processing protein " + proteinId);
for (Integer scanId : scans.keySet()) {
EValueServer.getEvalue(scanId, proteinId);
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
EValueServer.init(args);
Map<Integer,Scan> scans = conf.getScans();
DbUtil.initDatabase();
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Integer> proteinIds = new ArrayList<Integer>();
try {
ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)");
rs = ps.executeQuery();
while (rs.next()) {
proteinIds.add(rs.getInt(1));
}
} catch (SQLException e) {
log.error("Error loading proteins from database", e);
throw new RuntimeException(e);
} finally {
DbUtil.close(con, ps, rs);
}
for (Integer proteinId : proteinIds) {
log.debug("Processing protein " + proteinId);
for (Integer scanId : scans.keySet()) {
EValueServer.getEvalue(scanId, proteinId);
}
}
}
| public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
EValueServer.init(args);
Map<Integer,Scan> scans = conf.getScans();
DbUtil.initDatabase();
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
List<Integer> proteinIds = new ArrayList<Integer>();
try {
ps = con.prepareStatement("select protein_id from t_status where evalue < 0.0024 group by protein_id order by count(*)");
rs = ps.executeQuery();
while (rs.next()) {
proteinIds.add(rs.getInt(1));
}
} catch (SQLException e) {
log.error("Error loading proteins from database", e);
throw new RuntimeException(e);
} finally {
DbUtil.close(con, ps, rs);
}
for (Integer proteinId : proteinIds) {
System.out.println("Processing protein " + proteinId);
for (Integer scanId : scans.keySet()) {
EValueServer.getEvalue(scanId, proteinId);
}
}
}
|
diff --git a/EclipseProject/src/weatherOracle/activity/NotificationActivity.java b/EclipseProject/src/weatherOracle/activity/NotificationActivity.java
index 3689dca..a7fb90a 100644
--- a/EclipseProject/src/weatherOracle/activity/NotificationActivity.java
+++ b/EclipseProject/src/weatherOracle/activity/NotificationActivity.java
@@ -1,318 +1,318 @@
package weatherOracle.activity;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import weatherOracle.filter.ConditionRule;
import weatherOracle.filter.Filter;
import weatherOracle.notification.Notification;
import weatherOracle.notification.NotificationStore;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
public class NotificationActivity extends Activity {
/**
* List of Notifications to be displayed by this activity
*/
List<Notification> notificationList;
LinearLayout mainView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
instance=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_activity);
mainView = (LinearLayout)findViewById(R.id.notification_activity_linear_layout);
populateNotificationList();
displayNotifications();
}
private void updateDisplay(){
mainView.removeAllViews();
populateNotificationList();
displayNotifications();
}
public void onResume() {
instance=this;
super.onResume();
updateDisplay();
}
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
if(hasFocus) {
updateDisplay();
} else {
mainView.removeAllViews();
}
}
/**
* Populate and update the notificationList Field
*/
private void populateNotificationList() {
notificationList = NotificationStore.getNotifications();
}
private void displayNotifications() {
try {
if(notificationList.size()==1)
- statusBarNotification(R.drawable.clouds,
+ statusBarNotification(R.drawable.icon,
notificationList.get(0).getName(),
"WeatherOracle",
notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName()
+ ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString());
else if(notificationList.size()>1)
- statusBarNotification(R.drawable.clouds,
+ statusBarNotification(R.drawable.icon,
notificationList.size()+" new notifications",
"WeatherOracle",
notificationList.size()+" new notifications");
} catch (Exception e) {
}
for (int i = 0;i<notificationList.size();i++) {
boolean firstIteration = false;
boolean lastIteration = false;
if(i == 0){
firstIteration = true;
}
if(i == notificationList.size() - 1){
lastIteration = true;
}
// parentll represents an entire on screen notification element; it's first child is
// the top divider ... its next is all of the main content of the notification ... and
// its third and last child is the bottom divider
final LinearLayout parentll = new LinearLayout(this);
parentll.setOrientation(LinearLayout.VERTICAL);
// set up top divider and add to parent
final View divider = new View(this);
divider.setBackgroundColor(R.color.grey);
LayoutParams dividerParams;
if(firstIteration){
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider, dividerParams);
// set up ll view that will hold main content of notification
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(8, 4, 8, 4);
parentll.addView(ll,layoutParams);
// set up bottom divider and add to parent
final View divider2 = new View(this);
divider2.setBackgroundColor(R.color.grey);
LayoutParams dividerParams2;
if(lastIteration){
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider2, dividerParams2);
RelativeLayout nameAndDetails = new RelativeLayout(this);
ll.addView(nameAndDetails);
// LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50);
// ll.addView(nameAndDetails, nameParams);
TextView name = new TextView(getApplicationContext());
name.setText(notificationList.get(i).getName());
name.setTextSize(2,25);
name.setTextColor(Color.BLACK);
nameAndDetails.addView(name);
ll.setOrientation(0);
// ll.addView(name);
final int index = i;
Button internet = new Button(getApplicationContext());
internet.setGravity(Gravity.CENTER_VERTICAL);
internet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
URL url;
/*url = new URL("http://forecast.weather.gov/MapClick.php?lat="
+ lat + "&lon=" + lon);*/
Filter currentFilter = notificationList.get(index).getFilter();
double lat = currentFilter.getLocation().lat;
double lon = currentFilter.getLocation().lon;
String conditionSpecifier = "";
int timeSpecifier = 0;
long timeDiff = 0;
TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone();
for(ConditionRule cr : currentFilter.getConditionRules()) {
if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) {
conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&";
}
}
if (notificationList.get(index).getWeatherData() != null) {
timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime()
- Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600);
timeSpecifier = (int) timeDiff;
if (timeSpecifier < 0) {
timeSpecifier = 0;
}
}
url = new URL("http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Intent myIntent = new Intent(v.getContext(), InternetForecast.class);
myIntent.putExtra("url", url);
startActivity(myIntent);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
internet.setText("Details");
if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) {
//dont add the connect to internet button
} else {
nameAndDetails.addView(internet);
LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams();
params.setMargins(0, 6, -2, 4);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
internet.setLayoutParams(params); //causes layout update
}
ll.setOrientation(1);
if (notificationList.get(i).getWeatherData() != null) {
TextView conditionTag = new TextView(getApplicationContext());
//conditionTag.setText();
conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() +
"\nWill Occur during:\n\t" + notificationList.get(i).getDays());
ll.addView(conditionTag);
}
if (notificationList.get(i).getFilter() != null) {
TextView locationTag = new TextView(getApplicationContext());
String location = "";
if (notificationList.get(i).getFilter().getLocationName() != null) {
location = notificationList.get(i).getFilter().getLocationName();
locationTag.setText("Location:\n\t " + location);
ll.addView(locationTag);
}
TextView conditionTag = new TextView(getApplicationContext());
conditionTag.setText("With Condition(s):");
ll.addView(conditionTag);
List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules());
for(int j = 0 ;j < conditions.size(); j++) {
TextView condition = new TextView(getApplicationContext());
condition.setText("\t" +conditions.get(j).toString());
ll.addView(condition);
}
}
mainView.addView(parentll);
}
}
public void statusBarNotification(int icon,CharSequence tickerText,CharSequence contentTitle,CharSequence contentText)
{
//Example: statusBarNotification(R.drawable.rain,"It's raining!","WeatherOracle","It's raining outside! Get me my galoshes");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long when = System.currentTimeMillis();
android.app.Notification notification = new android.app.Notification(icon, tickerText, when);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(this, HomeMenuActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
private static class Updater implements Runnable {
public void run() {
instance.updateDisplay();
}
}
private static NotificationActivity instance=null;
public static void asyncUpdate(){
synchronized(instance){
instance.runOnUiThread(new Updater());
}
}
}
| false | true | private void displayNotifications() {
try {
if(notificationList.size()==1)
statusBarNotification(R.drawable.clouds,
notificationList.get(0).getName(),
"WeatherOracle",
notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName()
+ ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString());
else if(notificationList.size()>1)
statusBarNotification(R.drawable.clouds,
notificationList.size()+" new notifications",
"WeatherOracle",
notificationList.size()+" new notifications");
} catch (Exception e) {
}
for (int i = 0;i<notificationList.size();i++) {
boolean firstIteration = false;
boolean lastIteration = false;
if(i == 0){
firstIteration = true;
}
if(i == notificationList.size() - 1){
lastIteration = true;
}
// parentll represents an entire on screen notification element; it's first child is
// the top divider ... its next is all of the main content of the notification ... and
// its third and last child is the bottom divider
final LinearLayout parentll = new LinearLayout(this);
parentll.setOrientation(LinearLayout.VERTICAL);
// set up top divider and add to parent
final View divider = new View(this);
divider.setBackgroundColor(R.color.grey);
LayoutParams dividerParams;
if(firstIteration){
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider, dividerParams);
// set up ll view that will hold main content of notification
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(8, 4, 8, 4);
parentll.addView(ll,layoutParams);
// set up bottom divider and add to parent
final View divider2 = new View(this);
divider2.setBackgroundColor(R.color.grey);
LayoutParams dividerParams2;
if(lastIteration){
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider2, dividerParams2);
RelativeLayout nameAndDetails = new RelativeLayout(this);
ll.addView(nameAndDetails);
// LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50);
// ll.addView(nameAndDetails, nameParams);
TextView name = new TextView(getApplicationContext());
name.setText(notificationList.get(i).getName());
name.setTextSize(2,25);
name.setTextColor(Color.BLACK);
nameAndDetails.addView(name);
ll.setOrientation(0);
// ll.addView(name);
final int index = i;
Button internet = new Button(getApplicationContext());
internet.setGravity(Gravity.CENTER_VERTICAL);
internet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
URL url;
/*url = new URL("http://forecast.weather.gov/MapClick.php?lat="
+ lat + "&lon=" + lon);*/
Filter currentFilter = notificationList.get(index).getFilter();
double lat = currentFilter.getLocation().lat;
double lon = currentFilter.getLocation().lon;
String conditionSpecifier = "";
int timeSpecifier = 0;
long timeDiff = 0;
TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone();
for(ConditionRule cr : currentFilter.getConditionRules()) {
if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) {
conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&";
}
}
if (notificationList.get(index).getWeatherData() != null) {
timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime()
- Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600);
timeSpecifier = (int) timeDiff;
if (timeSpecifier < 0) {
timeSpecifier = 0;
}
}
url = new URL("http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Intent myIntent = new Intent(v.getContext(), InternetForecast.class);
myIntent.putExtra("url", url);
startActivity(myIntent);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
internet.setText("Details");
if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) {
//dont add the connect to internet button
} else {
nameAndDetails.addView(internet);
LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams();
params.setMargins(0, 6, -2, 4);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
internet.setLayoutParams(params); //causes layout update
}
ll.setOrientation(1);
if (notificationList.get(i).getWeatherData() != null) {
TextView conditionTag = new TextView(getApplicationContext());
//conditionTag.setText();
conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() +
"\nWill Occur during:\n\t" + notificationList.get(i).getDays());
ll.addView(conditionTag);
}
if (notificationList.get(i).getFilter() != null) {
TextView locationTag = new TextView(getApplicationContext());
String location = "";
if (notificationList.get(i).getFilter().getLocationName() != null) {
location = notificationList.get(i).getFilter().getLocationName();
locationTag.setText("Location:\n\t " + location);
ll.addView(locationTag);
}
TextView conditionTag = new TextView(getApplicationContext());
conditionTag.setText("With Condition(s):");
ll.addView(conditionTag);
List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules());
for(int j = 0 ;j < conditions.size(); j++) {
TextView condition = new TextView(getApplicationContext());
condition.setText("\t" +conditions.get(j).toString());
ll.addView(condition);
}
}
mainView.addView(parentll);
}
}
| private void displayNotifications() {
try {
if(notificationList.size()==1)
statusBarNotification(R.drawable.icon,
notificationList.get(0).getName(),
"WeatherOracle",
notificationList.get(0).getName() + ". Location:" + notificationList.get(0).getFilter().getLocationName()
+ ". First Occur at" + notificationList.get(0).getWeatherData().get(0).getTimeString());
else if(notificationList.size()>1)
statusBarNotification(R.drawable.icon,
notificationList.size()+" new notifications",
"WeatherOracle",
notificationList.size()+" new notifications");
} catch (Exception e) {
}
for (int i = 0;i<notificationList.size();i++) {
boolean firstIteration = false;
boolean lastIteration = false;
if(i == 0){
firstIteration = true;
}
if(i == notificationList.size() - 1){
lastIteration = true;
}
// parentll represents an entire on screen notification element; it's first child is
// the top divider ... its next is all of the main content of the notification ... and
// its third and last child is the bottom divider
final LinearLayout parentll = new LinearLayout(this);
parentll.setOrientation(LinearLayout.VERTICAL);
// set up top divider and add to parent
final View divider = new View(this);
divider.setBackgroundColor(R.color.grey);
LayoutParams dividerParams;
if(firstIteration){
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider, dividerParams);
// set up ll view that will hold main content of notification
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(8, 4, 8, 4);
parentll.addView(ll,layoutParams);
// set up bottom divider and add to parent
final View divider2 = new View(this);
divider2.setBackgroundColor(R.color.grey);
LayoutParams dividerParams2;
if(lastIteration){
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 2);
} else {
dividerParams2 = new LayoutParams(LayoutParams.FILL_PARENT, 1);
}
//dividerParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
parentll.addView(divider2, dividerParams2);
RelativeLayout nameAndDetails = new RelativeLayout(this);
ll.addView(nameAndDetails);
// LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 50);
// ll.addView(nameAndDetails, nameParams);
TextView name = new TextView(getApplicationContext());
name.setText(notificationList.get(i).getName());
name.setTextSize(2,25);
name.setTextColor(Color.BLACK);
nameAndDetails.addView(name);
ll.setOrientation(0);
// ll.addView(name);
final int index = i;
Button internet = new Button(getApplicationContext());
internet.setGravity(Gravity.CENTER_VERTICAL);
internet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
URL url;
/*url = new URL("http://forecast.weather.gov/MapClick.php?lat="
+ lat + "&lon=" + lon);*/
Filter currentFilter = notificationList.get(index).getFilter();
double lat = currentFilter.getLocation().lat;
double lon = currentFilter.getLocation().lon;
String conditionSpecifier = "";
int timeSpecifier = 0;
long timeDiff = 0;
TimeZone filterTimeZone = notificationList.get(index).getWeatherData().get(0).getTimeZone();
for(ConditionRule cr : currentFilter.getConditionRules()) {
if (!conditionSpecifier.contains(ConditionRule.geturlSpecifier(cr.getCondition()))) {
conditionSpecifier += ConditionRule.geturlSpecifier(cr.getCondition()) + "&";
}
}
if (notificationList.get(index).getWeatherData() != null) {
timeDiff = (notificationList.get(index).getWeatherData().get(0).getMillisTime()
- Calendar.getInstance(filterTimeZone).getTimeInMillis())/(1000*3600);
timeSpecifier = (int) timeDiff;
if (timeSpecifier < 0) {
timeSpecifier = 0;
}
}
url = new URL("http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Log.d("NOTIFICATION ACTIVITY", "http://forecast.weather.gov/MapClick.php?"
+ conditionSpecifier
+ "&w3u=1&AheadHour="
+ timeSpecifier
+ "&Submit=Submit&FcstType=digital&textField1="
+ lat
+ "&textField2="
+ lon
+ "&site=all&unit=0&dd=0&bw=0");
Intent myIntent = new Intent(v.getContext(), InternetForecast.class);
myIntent.putExtra("url", url);
startActivity(myIntent);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
internet.setText("Details");
if((notificationList.get(i).getName().equals("No Internet Connection") || notificationList.get(i).getName().equals("No Notification Yet")) && notificationList.get(i).getFilter() == null && notificationList.get(i).getWeatherData() == null || notificationList.get(i).getName().contains("No data at location")) {
//dont add the connect to internet button
} else {
nameAndDetails.addView(internet);
LayoutParams params = (RelativeLayout.LayoutParams)internet.getLayoutParams();
params.setMargins(0, 6, -2, 4);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
internet.setLayoutParams(params); //causes layout update
}
ll.setOrientation(1);
if (notificationList.get(i).getWeatherData() != null) {
TextView conditionTag = new TextView(getApplicationContext());
//conditionTag.setText();
conditionTag.setText("Will First Occur on:\n\t" + notificationList.get(i).getWeatherData().get(0).getTimeString() +
"\nWill Occur during:\n\t" + notificationList.get(i).getDays());
ll.addView(conditionTag);
}
if (notificationList.get(i).getFilter() != null) {
TextView locationTag = new TextView(getApplicationContext());
String location = "";
if (notificationList.get(i).getFilter().getLocationName() != null) {
location = notificationList.get(i).getFilter().getLocationName();
locationTag.setText("Location:\n\t " + location);
ll.addView(locationTag);
}
TextView conditionTag = new TextView(getApplicationContext());
conditionTag.setText("With Condition(s):");
ll.addView(conditionTag);
List<ConditionRule> conditions = new ArrayList<ConditionRule>(notificationList.get(i).getFilter().getConditionRules());
for(int j = 0 ;j < conditions.size(); j++) {
TextView condition = new TextView(getApplicationContext());
condition.setText("\t" +conditions.get(j).toString());
ll.addView(condition);
}
}
mainView.addView(parentll);
}
}
|